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:com.google.gwt.benchmark.compileserver.server.manager.BenchmarkReporter.java

private boolean postResultToServer(String json) {
    OutputStream out = null;/*from w  w w.ja v a2 s  .c  om*/
    try {

        HttpURLConnection httpCon = httpURLConnectionFactory.create();
        httpCon.addRequestProperty("auth", reporterSecret);
        httpCon.setDoOutput(true);
        httpCon.setRequestMethod("PUT");

        out = httpCon.getOutputStream();
        out.write(json.getBytes("UTF-8"));

        if (httpCon.getResponseCode() == HTTP_OK) {
            return true;
        }

    } catch (IOException e) {
        logger.log(Level.WARNING, "Could not post results to server", e);
    } finally {
        IOUtils.closeQuietly(out);
    }
    return false;
}

From source file:org.graylog2.alarmcallbacks.hipchat.HipChatTrigger.java

public void trigger(AlertCondition condition, AlertCondition.CheckResult alert) throws AlarmCallbackException {
    final URL url;
    try {//from  ww  w . j av  a  2 s .  com
        if (Strings.isNullOrEmpty(apiURL)) {
            url = new URL(
                    "https://api.hipchat.com/v2/room/" + URLEncoder.encode(room, "UTF-8") + "/notification");
        } else {
            url = new URL(apiURL + "/v2/room/" + URLEncoder.encode(room, "UTF-8") + "/notification");
        }
    } catch (MalformedURLException | UnsupportedEncodingException e) {
        throw new AlarmCallbackException("Error while constructing URL of HipChat API.", e);
    }

    final HttpURLConnection conn;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Authorization", "Bearer " + apiToken);
        conn.addRequestProperty("Content-Type", "application/json");
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not open connection to HipChat API", e);
    }

    try (final OutputStream outputStream = conn.getOutputStream()) {
        outputStream.write(objectMapper.writeValueAsBytes(buildRoomNotification(condition, alert)));
        outputStream.flush();

        if (conn.getResponseCode() != 204) {
            throw new AlarmCallbackException("Unexpected HTTP response status " + conn.getResponseCode());
        }
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not POST event trigger to HipChat API", e);
    }
}

From source file:edu.pdx.cecs.orcycle.Uploader.java

private boolean uploadOneSegment(long currentNoteId) {
    boolean result = false;
    final String postUrl = mCtx.getResources().getString(R.string.post_url);

    try {/*from   w  w w. jav  a  2s  .co m*/
        URL url = new URL(postUrl);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("Cycleatl-Protocol-Version", "4");

        SegmentData segmentData = SegmentData.fetchSegment(mCtx, currentNoteId);
        JSONObject json = segmentData.getJSON();
        String deviceId = userId;

        DataOutputStream stream = new DataOutputStream(conn.getOutputStream());
        stream.writeBytes(makeContentField("ratesegment", json.toString()));
        stream.writeBytes(makeContentField("version", String.valueOf(kSaveNoteProtocolVersion)));
        stream.writeBytes(makeContentField("device", deviceId));
        stream.writeBytes(contentFieldPrefix);
        stream.flush();
        stream.close();

        int serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();
        Log.v(MODULE_TAG, "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
        if (serverResponseCode == 201 || serverResponseCode == 202) {
            segmentData.updateSegmentStatus(SegmentData.STATUS_SENT);
            result = true;
        }
    } catch (IllegalStateException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }
    return result;
}

From source file:ee.ria.xroad.proxy.clientproxy.WsdlRequestProcessor.java

HttpURLConnection createConnection(SoapMessageImpl message) throws Exception {
    URL url = new URL("http://127.0.0.1:" + SystemProperties.getClientProxyHttpPort());

    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setDoInput(true);//from   www .  java2  s. c o m
    con.setDoOutput(true);
    // Use the same timeouts as client proxy to server proxy connections.
    con.setConnectTimeout(SystemProperties.getClientProxyTimeout());
    con.setReadTimeout(SystemProperties.getClientProxyHttpClientTimeout());
    con.setRequestMethod("POST");

    con.setRequestProperty(HttpHeaders.CONTENT_TYPE,
            MimeUtils.contentTypeWithCharset(MimeTypes.TEXT_XML, StandardCharsets.UTF_8.name()));

    IOUtils.write(message.getBytes(), con.getOutputStream());

    if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(
                "Received HTTP error: " + con.getResponseCode() + " - " + con.getResponseMessage());
    }

    return con;
}

From source file:babel.util.language.GoogleLangDetector.java

/**
 * Forms an HTTP request, sends it using GET method and returns the result of
 * the request as a JSONObject.//  w  ww .j  ava2s . com
 *
 * @param url the URL to query for a JSONObject.
 */
protected JSONObject retrieveJSON(final URL url) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", m_referrer);
        uc.setRequestMethod("GET");
        uc.setDoOutput(true);

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            uc.getInputStream().close();

            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("Error retrieving detection result : " + ex.toString(), ex);
    }
}

From source file:com.kotcrab.vis.editor.CrashReporter.java

private void sendReport() {
    progressBox.setVisible(true);//w w w .java 2 s  .c  om

    Task<Void> task = new Task<Void>() {
        @Override
        public Void call() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(
                        REPORT_URL + "?filename=" + reportFile.getName()).openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                OutputStream os = connection.getOutputStream();

                if (detailsTextArea.getText().equals("") == false) {
                    os.write(("Details: " + detailsTextArea.getText()).getBytes());
                    os.write('\n');
                }
                os.write(report.getBytes());
                os.flush();
                os.close();

                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String s;
                while ((s = in.readLine()) != null)
                    System.out.println("Server response: " + s);
                in.close();

                System.out.println("Crash report sent");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void succeeded() {
            Platform.exit();
        }

        @Override
        protected void failed() {
            Platform.exit();
        }
    };
    new Thread(task).start();
}

From source file:de.thingweb.discovery.TDRepository.java

/**
 * Adds a ThingDescription to Repository
 * /*from w ww .  j  a va 2 s.  c  om*/
 * @param content JSON-LD
 * @return key of entry in repository
 * @throws Exception in case of error
 */
public String addTD(byte[] content) throws Exception {
    URL url = new URL("http://" + repository_uri + "/td");
    HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
    httpCon.setDoOutput(true);
    httpCon.setRequestProperty("content-type", "application/ld+json");
    httpCon.setRequestMethod("POST");
    OutputStream out = httpCon.getOutputStream();
    out.write(content);
    out.close();

    InputStream is = httpCon.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int b;
    while ((b = is.read()) != -1) {
        baos.write(b);
    }

    int responseCode = httpCon.getResponseCode();

    httpCon.disconnect();

    String key = ""; // new String(baos.toByteArray());

    if (responseCode != 201) {
        // error
        throw new RuntimeException("ResponseCodeError: " + responseCode);
    } else {
        Map<String, List<String>> hf = httpCon.getHeaderFields();
        List<String> los = hf.get("Location");
        if (los != null && los.size() > 0) {
            key = los.get(0);
        }
    }

    return key;
}

From source file:gr.uoc.nlp.opinion.analysis.suggestion.ElasticSearchIntegration.java

/**
 *
 * @param commentID/*from  w w w .  ja  v a2 s .  c o m*/
 * @param sentenceID
 * @param document
 */
public void sendToElasticSearch(String commentID, String sentenceID, String document) {

    try {
        //fix uri
        String url = elasticSearchURI + commentID + "_" + sentenceID;

        //open connection
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");

        //append data to http packet
        String data = "{\"comment\": \"" + commentID + "\"," + " \"sentence\": \"" + sentenceID + "\","
                + " \"document\": \"" + document + "\"}";

        //write data to http socket
        try (OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream())) {
            out.write(data);
            out.close();
        }

        //get response data
        String line = "";
        try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {

            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        }

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

From source file:com.example.httpjson.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/* w ww. ja  v  a2 s  .  c  om*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                if (a == 401) {
                    response = new Response(a, conn.getHeaderFields(), new byte[] {});
                }
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:org.exoplatform.shareextension.service.UploadAction.java

@Override
protected boolean doExecute() {
    String id = uploadInfo.uploadId;
    String boundary = "----------------------------" + id;
    String CRLF = "\r\n";
    int status = -1;
    OutputStream output = null;//from   w ww  . j a  v a  2 s  .  c o m
    PrintWriter writer = null;
    try {
        // Open a connection to the upload web service
        StringBuffer stringUrl = new StringBuffer(postInfo.ownerAccount.serverUrl).append("/portal")
                .append(ExoConstants.DOCUMENT_UPLOAD_PATH_REST).append("?uploadId=").append(id);
        URL uploadUrl = new URL(stringUrl.toString());
        HttpURLConnection uploadReq = (HttpURLConnection) uploadUrl.openConnection();
        uploadReq.setDoOutput(true);
        uploadReq.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        // Pass the session cookies for authentication
        CookieStore store = ExoConnectionUtils.cookiesStore;
        if (store != null) {
            StringBuffer cookieString = new StringBuffer();
            for (Cookie cookie : store.getCookies()) {
                cookieString.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
            }
            uploadReq.addRequestProperty("Cookie", cookieString.toString());
        }
        ExoConnectionUtils.setUserAgent(uploadReq);
        // Write the form data
        output = uploadReq.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"file\"; filename=\""
                + uploadInfo.fileToUpload.documentName + "\"").append(CRLF);
        writer.append("Content-Type: " + uploadInfo.fileToUpload.documentMimeType).append(CRLF);
        writer.append(CRLF).flush();
        byte[] buf = new byte[1024];
        while (uploadInfo.fileToUpload.documentData.read(buf) != -1) {
            output.write(buf);
        }
        output.flush();
        writer.append(CRLF).flush();
        writer.append("--" + boundary + "--").append(CRLF).flush();
        // Execute the connection and retrieve the status code
        status = uploadReq.getResponseCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while uploading " + uploadInfo.fileToUpload, e);
    } finally {
        if (uploadInfo != null && uploadInfo.fileToUpload != null
                && uploadInfo.fileToUpload.documentData != null)
            try {
                uploadInfo.fileToUpload.documentData.close();
            } catch (IOException e1) {
                Log.e(LOG_TAG, "Error while closing the upload stream", e1);
            }
        if (output != null)
            try {
                output.close();
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error while closing the connection", e);
            }
        if (writer != null)
            writer.close();
    }
    if (status < HttpURLConnection.HTTP_OK || status >= HttpURLConnection.HTTP_MULT_CHOICE) {
        // Exit if the upload went wrong
        return listener.onError("Could not upload the file " + uploadInfo.fileToUpload.documentName);
    }
    status = -1;
    try {
        // Prepare the request to save the file in JCR
        String stringUrl = postInfo.ownerAccount.serverUrl + "/portal"
                + ExoConstants.DOCUMENT_CONTROL_PATH_REST;
        Uri moveUri = Uri.parse(stringUrl);
        moveUri = moveUri.buildUpon().appendQueryParameter("uploadId", id)
                .appendQueryParameter("action", "save")
                .appendQueryParameter("workspaceName", DocumentHelper.getInstance().workspace)
                .appendQueryParameter("driveName", uploadInfo.drive)
                .appendQueryParameter("currentFolder", uploadInfo.folder)
                .appendQueryParameter("fileName", uploadInfo.fileToUpload.documentName).build();
        HttpGet moveReq = new HttpGet(moveUri.toString());
        // Execute the request and retrieve the status code
        HttpResponse move = ExoConnectionUtils.httpClient.execute(moveReq);
        status = move.getStatusLine().getStatusCode();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Error while saving " + uploadInfo.fileToUpload + " in JCR", e);
    }
    boolean ret = false;
    if (status >= HttpStatus.SC_OK && status < HttpStatus.SC_MULTIPLE_CHOICES) {
        ret = listener.onSuccess("File " + uploadInfo.fileToUpload.documentName + "uploaded successfully");
    } else {
        ret = listener.onError("Could not save the file " + uploadInfo.fileToUpload.documentName);
    }
    return ret;
}