Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoOutput.

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

From source file:bakuposter.gcm.server.POST2GCMessage.java

public static void post(String apiKey, Content content) {

    try {/*from w  w  w  .j  a va2  s  .c  om*/
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Authorization", "key=" + apiKey);
        conn.setDoOutput(true);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(content.getRegistration_ids().get(0));
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        mapper.writeValue(wr, content);
        wr.flush();
        wr.close();
        int responseCode = conn.getResponseCode();
        System.out.println("responseCode = " + responseCode);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.shopgun.android.sdk.network.impl.HttpURLNetwork.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException {
    byte[] body = request.getBody();
    if (body != null) {
        connection.setDoOutput(true);
        connection.addRequestProperty("Content-Type", request.getBodyContentType());
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(body);/*from  www . ja  va  2 s .co m*/
        out.close();
    }
}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {/*w w w.j a  va2s.c o m*/
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:io.github.retz.executor.FileManager.java

private static void fetchHTTPFile(String file, String dest) throws IOException {
    URL url = new URL(file);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");

    conn.setDoOutput(true);
    java.nio.file.Path path = Paths.get(file).getFileName();
    if (path == null) {
        throw new FileNotFoundException(file);
    }/*w  w w.  jav  a 2s  .  c  o  m*/
    String filename = path.toString();
    InputStream input = null;
    try (FileOutputStream output = new FileOutputStream(dest + "/" + filename)) {
        input = conn.getInputStream();
        byte[] buffer = new byte[65536];
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        LOG.debug(e.getMessage());
        throw e;
    } finally {
        if (input != null)
            input.close();
    }
    conn.disconnect();
    LOG.info("Download finished: {}", file);
}

From source file:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;//  w w w  .  j a v  a 2s .  co m

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:com.google.api.ads.adwords.awreporting.server.appengine.exporter.ReportExporterAppEngine.java

public static void html2PdfOverNet(InputStream htmlSource, ReportWriter reportWriter) {
    try {//from www . jav a2s  .  c  om
        URL url = new URL(HTML_2_PDF_SERVER_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/html");
        connection.setRequestProperty("charset", "utf-8");
        connection.setUseCaches(false);

        DataOutputStream send = new DataOutputStream(connection.getOutputStream());
        send.write(IOUtils.toByteArray(htmlSource));
        send.flush();

        // Read from connection
        reportWriter.write(connection.getInputStream());

        send.close();

        connection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:io.github.retz.scheduler.MesosHTTPFetcher.java

private static Optional<String> fetchDirectory(String slave, String frameworkId, String executorId) {
    try {//from  ww  w .ja v a  2  s. c  o m
        URL url = new URL("http://" + slave + "/state");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setDoOutput(true);
        return extractDirectory(conn.getInputStream(), frameworkId, executorId);

    } catch (MalformedURLException e) {
        // REVIEW: catch(MalformedURLException) clause can be removed because it <: IOException
        return Optional.empty();
    } catch (IOException e) {
        return Optional.empty();
    }
}

From source file:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *///from  ww w  . j a va2 s  .c  o  m
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:com.surfs.storage.common.util.HttpUtils.java

public static String invokeHttpForGet(String path, String... agrs) throws IOException {
    URL url = new URL(path);
    LogFactory.info("rest url:" + url.toString());
    HttpURLConnection con = null;
    try {//from   w  ww .  j ava2s .c om
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setConnectTimeout(10000);
        con.setReadTimeout(1000 * 60 * 30);
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        for (String string : agrs) {
            con.setRequestProperty("Content-type", "application/json");
            con.setRequestMethod("POST");
            OutputStream out = con.getOutputStream();
            out.write(string.getBytes("UTF-8"));
        }

        if (con.getResponseCode() != 200)
            throw new ConnectException(con.getResponseMessage());

        InputStream is = con.getInputStream();

        return readResponse(is);

    } catch (IOException e) {
        throw e;
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:com.company.project.core.connector.HttpClientHelper.java

public static String getResponseStringFromConn(HttpURLConnection conn, String payLoad) throws IOException {

    // Send the http message payload to the server.
    if (payLoad != null) {
        conn.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
        osw.write(payLoad);/*from   w w  w .  j  a  v  a 2  s .  c om*/
        osw.flush();
        osw.close();
    }

    // Get the message response from the server.
    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line = "";
    StringBuffer stringBuffer = new StringBuffer();
    while ((line = br.readLine()) != null) {
        stringBuffer.append(line);
    }

    br.close();

    return stringBuffer.toString();
}