Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

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

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

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

Usage

From source file:mendhak.teamcity.stash.api.StashClient.java

private String PostBuildStatusToStash(String targetURL, String body, String authHeader) {

    HttpURLConnection connection = null;
    try {//w  ww . ja  v  a 2 s  .  co m

        Logger.LogInfo("Sending build status to " + targetURL);
        Logger.LogInfo("With body: " + body);
        Logger.LogInfo("Auth header: " + authHeader);

        connection = GetConnection(targetURL);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        connection.setRequestProperty("Content-Length", String.valueOf(body.getBytes().length));
        connection.setRequestProperty("Authorization", "Basic " + authHeader);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(body);
        wr.flush();
        wr.close();

        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuilder response = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append("\r\n");
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        Logger.LogError("Could not send data to Stash. ", e);
    } finally {

        if (connection != null) {
            connection.disconnect();
        }
    }

    return null;

}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param fileName/*from w  w w  .jav a2  s .c o  m*/
 * @param urlStr
 * @param isSiteFile
 * @param propChgListener
 */
public void transferFile(final String fileName, final String urlStr, final boolean isSiteFile,
        final PropertyChangeListener propChgListener) {

    final String prgName = HttpLargeFileTransfer.class.toString();

    final File file = new File(fileName);
    if (file.exists()) {
        final long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected OutputStream fos = null;
                protected int nChunks = 0;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);
                        fis = new FileInputStream(file);

                        nChunks = (int) (fileSize / MAX_CHUNK_SIZE);
                        if (fileSize % MAX_CHUNK_SIZE > 0) {
                            nChunks++;
                        }

                        byte[] buf = new byte[BUFFER_SIZE];
                        long bytesRemaining = fileSize;

                        String clientID = String.valueOf((long) (Long.MIN_VALUE * Math.random()));

                        URL url = new URL(urlStr);

                        UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);

                        for (int i = 0; i < nChunks; i++) {
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                            if (i == nChunks - 1) {
                                Thread.sleep(500);
                                int x = 0;
                                x++;
                            }

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("PUT");
                            conn.setDoOutput(true);
                            conn.setDoInput(true);
                            conn.setUseCaches(false);

                            int chunkSize = (int) ((bytesRemaining > MAX_CHUNK_SIZE) ? MAX_CHUNK_SIZE
                                    : bytesRemaining);
                            bytesRemaining -= chunkSize;

                            conn.setRequestProperty("Content-Type", "application/octet-stream");
                            conn.setRequestProperty("Content-Length", String.valueOf(chunkSize));

                            conn.setRequestProperty(CLIENT_ID_HEADER, clientID);
                            conn.setRequestProperty(FILE_NAME_HEADER, fileName);
                            conn.setRequestProperty(FILE_CHUNK_COUNT_HEADER, String.valueOf(nChunks));
                            conn.setRequestProperty(FILE_CHUNK_HEADER, String.valueOf(i));
                            conn.setRequestProperty(SERVICE_NUMBER, "10");
                            conn.setRequestProperty(IS_SITE_FILE, Boolean.toString(isSiteFile));

                            fos = conn.getOutputStream();

                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, (int)((double)chunkSize / BUFFER_SIZE));
                            int cnt = 0;
                            int bytesRead = 0;
                            while (bytesRead < chunkSize) {
                                int read = fis.read(buf);
                                if (read == -1) {
                                    break;

                                } else if (read > 0) {
                                    bytesRead += read;
                                    fos.write(buf, 0, read);
                                }
                                cnt++;
                                //firePropertyChange(prgName, cnt-1, cnt);
                            }
                            fos.close();

                            if (conn.getResponseCode() != HttpServletResponse.SC_OK) {
                                System.err.println(
                                        conn.getResponseMessage() + " " + conn.getResponseCode() + " ");
                                BufferedReader in = new BufferedReader(
                                        new InputStreamReader(conn.getErrorStream()));
                                String line = null;
                                StringBuilder sb = new StringBuilder();
                                while ((line = in.readLine()) != null) {
                                    sb.append(line);
                                    sb.append("\n");
                                }
                                System.out.println(sb.toString());
                                in.close();

                            } else {
                                System.err.println("OK");
                            }
                            //UIRegistry.getStatusBar().setProgressRange(prgName, 0, nChunks);
                            firePropertyChange(prgName, i - 1, i == nChunks - 1 ? Integer.MAX_VALUE : i);
                        }

                    } catch (IOException ex) {
                        errorMsg = ex.toString();
                    }

                    //firePropertyChange(prgName, 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(prgName);

                    UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Transmitting..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    System.out.println(evt.getPropertyName() + "  " + evt.getNewValue());
                    if (prgName.equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        if (value == Integer.MAX_VALUE) {
                            statusBar.setIndeterminate(prgName, true);
                            UIRegistry.writeSimpleGlassPaneMsg(
                                    getLocalizedMessage("Transfering data into the database."), 24);

                        } else {
                            statusBar.setValue(prgName, value);
                        }
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
}

From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java

/**
 * Post the formatted results to the gateway URL over HTTP 
 * //from   www . j a v a2s. c o  m
 * @param gatewayMessage String in the Stackdriver custom metrics JSON format containing the data points
 */
private void doSend(final String gatewayMessage) {
    HttpURLConnection urlConnection = null;

    try {
        if (proxy == null) {
            urlConnection = (HttpURLConnection) gatewayUrl.openConnection();
        } else {
            urlConnection = (HttpURLConnection) gatewayUrl.openConnection(proxy);
        }
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(timeoutInMillis);
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey);

        // Stackdriver's own implementation does not specify char encoding
        // to use. Let's take the simplest approach and at lest ensure that
        // if we have problems they can be reproduced in consistant ways.
        // See https://github.com/Stackdriver/stackdriver-custommetrics-java/blob/master/src/main/java/com/stackdriver/api/custommetrics/CustomMetricsPoster.java#L262
        // for details.
        urlConnection.getOutputStream().write(gatewayMessage.getBytes(ISO_8859_1));

        int responseCode = urlConnection.getResponseCode();
        if (responseCode != 200 && responseCode != 201) {
            logger.warn("Failed to send results to Stackdriver server: responseCode=" + responseCode
                    + " message=" + urlConnection.getResponseMessage());
        }
    } catch (Exception e) {
        logger.warn("Failure to send result to Stackdriver server", e);
    } finally {
        if (urlConnection != null) {
            try {
                InputStream in = urlConnection.getInputStream();
                in.close();
                InputStream err = urlConnection.getErrorStream();
                if (err != null) {
                    err.close();
                }
                urlConnection.disconnect();
            } catch (IOException e) {
                logger.warn("Error flushing http connection for one result, continuing");
                logger.debug("Stack trace for the http connection, usually a network timeout", e);
            }
        }

    }
}

From source file:de.wikilab.android.friendica01.TwAjax.java

private void runFileUpload() throws IOException {

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "d1934afa-f2e4-449b-99be-8be6ebfec594";
    Log.i("Andfrnd/TwAjax", "URL=" + getURL());
    URL url = new URL(getURL());
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs
    connection.setDoInput(true);
    connection.setDoOutput(true);/*from   w  w  w  . j a  v  a  2  s .  co  m*/
    connection.setUseCaches(false);

    // Enable POST method
    connection.setRequestMethod("POST");

    //generate auth header if user/pass are provided to this class
    if (this.myHttpAuthUser != null) {
        connection.setRequestProperty("Authorization", "Basic " + Base64
                .encodeToString((this.myHttpAuthUser + ":" + this.myHttpAuthPass).getBytes(), Base64.NO_WRAP));
    }
    //Log.i("Andfrnd","-->"+connection.getRequestProperty("Authorization")+"<--");

    connection.setRequestProperty("Host", url.getHost());
    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    for (NameValuePair nvp : myPostData) {
        outputStream.writeBytes(twoHyphens + boundary + lineEnd);
        outputStream.writeBytes("Content-Disposition: form-data; name=\"" + nvp.getName() + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd + nvp.getValue() + lineEnd);
    }
    for (PostFile pf : myPostFiles) {
        pf.writeToStream(outputStream, boundary);
    }
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    myHttpStatus = connection.getResponseCode();

    outputStream.flush();
    outputStream.close();

    if (myHttpStatus < 400) {
        myResult = convertStreamToString(connection.getInputStream());
    } else {
        myResult = convertStreamToString(connection.getErrorStream());
    }

    success = true;
}

From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java

private HttpURLConnection setupConnection(URL url, Map<String, String> parameters) throws IOException {
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10_000);/* w w  w . j a  va2 s  . c o  m*/
    connection.setConnectTimeout(15_000);
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);
    OutputStream os = connection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(buildParametersList(parameters));
    writer.flush();
    writer.close();
    os.close();
    return connection;
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private void downloadExternalFile(String url, File localDestination, ProgressListener listener)
        throws IOException {
    URL downloadUrl = new URL(url);
    HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestMethod("GET");
    connection.setDoInput(true);//from  ww w  . j  a  v  a 2 s  .co  m

    try {
        if (connection.getResponseCode() != 200) {
            throw new NonSuccessfulResponseCodeException("Bad response: " + connection.getResponseCode());
        }

        OutputStream output = new FileOutputStream(localDestination);
        InputStream input = connection.getInputStream();
        byte[] buffer = new byte[4096];
        int contentLength = connection.getContentLength();
        int read, totalRead = 0;

        while ((read = input.read(buffer)) != -1) {
            output.write(buffer, 0, read);
            totalRead += read;

            if (listener != null) {
                listener.onAttachmentProgress(contentLength, totalRead);
            }
        }

        output.close();
        Log.w(TAG, "Downloaded: " + url + " to: " + localDestination.getAbsolutePath());
    } catch (IOException ioe) {
        throw new PushNetworkException(ioe);
    } finally {
        connection.disconnect();
    }
}

From source file:io.lqd.sdk.model.LQNetworkRequest.java

public LQNetworkResponse sendRequest(String token) {
    String response = null;/*from  w ww. j ava 2s . c  o  m*/
    int responseCode = -1;
    InputStream err = null;
    OutputStream out = null;
    BufferedOutputStream bout = null;
    BufferedReader boin = null;
    HttpURLConnection connection = null;
    try {
        URL url = new URL(this.getUrl());
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(this.getHttpMethod());
        connection.setRequestProperty("Authorization", "Token " + token);
        connection.setRequestProperty("User-Agent", USER_AGENT);
        connection.setRequestProperty("Accept", "application/vnd.lqd.v1+json");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip");
        connection.setDoInput(true);
        if (this.getJSON() != null) {
            connection.setDoOutput(true);
            out = connection.getOutputStream();
            bout = new BufferedOutputStream(out);
            final StringEntity stringEntity = new StringEntity(this.getJSON(), "UTF-8");
            stringEntity.writeTo(bout);
        }
        responseCode = connection.getResponseCode();
        err = connection.getErrorStream();
        GZIPInputStream gzip = new GZIPInputStream(connection.getInputStream());
        boin = new BufferedReader(new InputStreamReader(gzip, "UTF-8"));
        response = boin.readLine();
    } catch (IOException e) {
        LQLog.http("Failed due to " + e + " responseCode " + responseCode);
        LQLog.http("Error " + inputStreamToString(err));
    } finally {
        if (connection != null)
            connection.disconnect();
        try {
            if (out != null)
                out.close();
        } catch (IOException e) {
        }
        try {
            if (err != null)
                err.close();
        } catch (IOException e) {
        }
        try {
            if (bout != null)
                bout.close();
        } catch (IOException e) {
        }
        try {
            if (boin != null)
                boin.close();
        } catch (IOException e) {
        }
    }
    if ((response != null) || ((responseCode >= 200) && (responseCode < 300))) {
        LQLog.http("HTTP Success " + response);
        return new LQNetworkResponse(responseCode, response);
    }
    return new LQNetworkResponse(responseCode);
}

From source file:com.asto.move.util.qcloud.pic.VideoCloud.java

/**
 * Stat ?/*w  ww. jav a  2 s  .  c o m*/
 * @param userid      ?,0
 * @param fileid      
 * @param info         ?
 * @return             ?0?
 */
public int Stat(String userid, String fileid, VideoInfo info) {
    String req_url = "http://" + QCLOUD_DOMAIN + "/" + m_appid + "/" + userid + "/" + fileid;
    String rsp = "";

    try {
        URL realUrl = new URL(req_url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        // set header
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "web.image.myqcloud.com");
        connection.setRequestProperty("user-agent", "qcloud-java-sdk");

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        // read rsp
        rsp = GetResponse(connection);
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }

    try {
        JSONObject jsonObject = new JSONObject(rsp);
        int code = jsonObject.getInt("code");
        String msg = jsonObject.getString("message");
        if (0 != code) {
            return SetError(code, msg);
        }

        info.url = jsonObject.getJSONObject("data").getString("file_url");
        info.fileid = jsonObject.getJSONObject("data").getString("file_fileid");
        info.upload_time = jsonObject.getJSONObject("data").getInt("file_upload_time");
        info.size = jsonObject.getJSONObject("data").getInt("file_size");
        info.sha = jsonObject.getJSONObject("data").getString("file_sha");
        info.status = jsonObject.getJSONObject("data").getInt("video_status");
        info.status_msg = jsonObject.getJSONObject("data").getString("video_status_msg");

        if (jsonObject.getJSONObject("data").has("video_play_time"))
            info.video_play_time = jsonObject.getJSONObject("data").getInt("video_play_time");
        if (jsonObject.getJSONObject("data").has("video_title"))
            info.video_title = jsonObject.getJSONObject("data").getString("video_title");
        if (jsonObject.getJSONObject("data").has("video_desc"))
            info.video_desc = jsonObject.getJSONObject("data").getString("video_desc");
        if (jsonObject.getJSONObject("data").has("video_cover_url"))
            info.video_cover_url = jsonObject.getJSONObject("data").getString("video_cover_url");
    } catch (JSONException e) {
        return SetError(-1, "json exception, e=" + e.toString());
    }
    return SetError(0, "success");
}

From source file:org.maikelwever.droidpile.backend.ApiConnecter.java

public String postData(ArrayList<NameValuePair> payload, String... data) throws IOException {
    if (data.length < 1) {
        throw new IllegalArgumentException("More than 1 argument is required.");
    }//from  ww  w  . ja  v a 2  s  .c o m

    String url = this.baseUrl;
    String suffix = "";
    for (String arg : data) {
        suffix += "/" + arg;
    }

    suffix += "/";

    Log.d("droidpile", "URL we will call: " + url + suffix);

    url += suffix;
    URL uri = new URL(url);
    InputStreamReader is;
    HttpURLConnection con;

    if (url.startsWith("https")) {
        con = (HttpsURLConnection) uri.openConnection();
    } else {
        con = (HttpURLConnection) uri.openConnection();
    }

    String urlParameters = URLEncodedUtils.format(payload, ENCODING);

    con.setDoInput(true);
    con.setDoOutput(true);
    con.setInstanceFollowRedirects(false);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("charset", ENCODING);
    con.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes(ENCODING).length));
    con.setUseCaches(false);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();
    is = new InputStreamReader(con.getInputStream(), ENCODING);

    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(is);
    String read = br.readLine();

    while (read != null) {
        sb.append(read);
        read = br.readLine();
    }
    String stringData = sb.toString();
    con.disconnect();
    return stringData;
}

From source file:RhodesService.java

public static boolean pingHost(String host) {
    HttpURLConnection conn = null;
    boolean hostExists = false;
    try {//from w ww.ja v  a  2 s.  c o  m
        URL url = new URL(host);
        HttpURLConnection.setFollowRedirects(false);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("HEAD");
        conn.setAllowUserInteraction(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(10000);
        conn.setReadTimeout(10000);

        hostExists = (conn.getContentLength() > 0);
        if (hostExists)
            Logger.I(TAG, "PING network SUCCEEDED.");
        else
            Logger.E(TAG, "PING network FAILED.");
    } catch (Exception e) {
        Logger.E(TAG, e);
    } finally {
        if (conn != null) {
            try {
                conn.disconnect();
            } catch (Exception e) {
                Logger.E(TAG, e);
            }
        }
    }

    return hostExists;
}