Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

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

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:com.cloudbees.workflow.Util.java

public static int postToJenkins(Jenkins jenkins, String url, String content, String contentType)
        throws IOException {
    String jenkinsUrl = jenkins.getRootUrl();
    URL urlObj = new URL(jenkinsUrl + url.replace("/jenkins/job/", "job/"));
    HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection();

    try {//www  .  j  av  a 2 s.  co  m
        conn.setRequestMethod("POST");

        // Set the crumb header, otherwise the POST may be rejected.
        NameValuePair crumbHeader = getCrumbHeaderNVP(jenkins);
        conn.setRequestProperty(crumbHeader.getName(), crumbHeader.getValue());

        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        if (content != null) {
            byte[] bytes = content.getBytes(Charset.forName("UTF-8"));

            conn.setDoOutput(true);

            conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
            final OutputStream os = conn.getOutputStream();
            try {
                os.write(bytes);
                os.flush();
            } finally {
                os.close();
            }
        }

        return conn.getResponseCode();
    } finally {
        conn.disconnect();
    }
}

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

public static int delete(URL uri, Map<String, List<String>> headers) {
    //DELETE delete = new DELETE(uri, headers);
    int s = 0;//from w  w w  .  j a  va 2s . c  o m
    HttpURLConnection httpURLConnection = null;
    try {
        httpURLConnection = (HttpURLConnection) uri.openConnection();
        if (headers != null) {
            for (String header : headers.keySet()) {
                for (String value : headers.get(header)) {
                    httpURLConnection.addRequestProperty(header, value);
                }
            }
        }
        httpURLConnection.setRequestMethod("DELETE");
        //httpURLConnection.connect();
        s = httpURLConnection.getResponseCode();
        Log.d("TAG", "Response of delete: " + String.valueOf(s));

    } catch (IOException exception) {
        exception.printStackTrace();
    } finally {
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }
    return s;
}

From source file:Main.java

private static String httpPost(String address, String params) {
    InputStream inputStream = null;
    HttpURLConnection urlConnection = null;
    try {//w  ww .j a  va  2  s.  c o m
        URL url = new URL(address);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setRequestMethod("POST");
        urlConnection.getOutputStream().write(params.getBytes());
        urlConnection.getOutputStream().flush();

        urlConnection.connect();
        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = urlConnection.getInputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            StringBuffer stringBuffer = new StringBuffer();
            while ((len = inputStream.read(buffer)) != -1) {
                stringBuffer.append(new String(buffer, 0, len));
            }
            return stringBuffer.toString();
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(inputStream);
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;

}

From source file:com.ibm.iot.auto.bluemix.samples.ui.Connection.java

private void disconnectIfRequired(HttpURLConnection connection) {
    if (connection != null) {
        connection.disconnect();
    }
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Gets the OAuth access token./*from   w ww  .java 2 s .c  om*/
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:dictinsight.utils.io.HttpUtils.java

public static List<String> getSvnConfServer(String url) {
    BufferedReader reader = null;
    HttpURLConnection connection = null;
    List<String> seedList = new ArrayList<String>();
    try {//w  w  w. j  a  va 2 s.c  o m
        URL srcUrl = new URL(url);
        connection = (HttpURLConnection) srcUrl.openConnection();
        connection.setConnectTimeout(1000 * 10);
        connection.connect();
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String rec;
        while ((rec = reader.readLine()) != null) {
            seedList.add(rec);
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + " error!");
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (connection != null)
            connection.disconnect();
    }
    return seedList;
}

From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *//*from   ww w  .j ava2s. c om*/
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the PoliceStations JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:a122016.rr.com.alertme.QueryUtils.java

/**
 * Make an HTTP request to the given URL and return a String as the response.
 *///www.  j  a  va  2s .  c o m
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the Places JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

From source file:com.nhncorp.lucy.security.xss.listener.SecurityUtils.java

public static String getContentTypeFromUrlConnection(String strUrl, ContentTypeCacheRepo contentTypeCacheRepo) {
    // cache ?  ?.
    String result = contentTypeCacheRepo.getContentTypeFromCache(strUrl);
    //System.out.println("getContentTypeFromCache : " + result);
    if (StringUtils.isNotEmpty(result)) {
        return result;
    }/*from ww  w. j  ava  2s  . c  o m*/

    HttpURLConnection con = null;

    try {
        URL url = new URL(strUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("HEAD");
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.connect();

        int resCode = con.getResponseCode();

        if (resCode != HttpURLConnection.HTTP_OK) {
            System.err.println("error");
        } else {
            result = con.getContentType();
            //System.out.println("content-type from response header: " + result);

            if (result != null) {
                contentTypeCacheRepo.addContentTypeToCache(strUrl, new ContentType(result, new Date()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }

    return result;

}

From source file:com.talk.demo.util.NetworkUtilities.java

public static void downloadPhoto(final String photoName) {
    // If there is no photo, we're done
    if (TextUtils.isEmpty(photoName)) {
        return;//from   w ww  .jav a2s. co  m
    }

    try {
        Log.i(TAG, "Downloading photo: " + DOWNLOAD_PHOTO_URI);
        // Request the photo from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(DOWNLOAD_PHOTO_URI + photoName + "/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap photo = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            Log.d(TAG, "file name : " + photoName);
            TalkUtil.createDirAndSaveFile(photo, photoName);
            // On pre-Honeycomb systems, it's important to call recycle on bitmaps
            photo.recycle();
        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + DOWNLOAD_PHOTO_URI);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + DOWNLOAD_PHOTO_URI);
    }
}