List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.joelapenna.foursquared.appwidget.stats.FoursquareHelper.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.//from ww w . ja v a 2s . com * * @param url The exact URL to request. * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. * @author Sections of this code contributed by jTribe (http://jtribe.com.au) */ protected static synchronized String getUrlContent(String sUrl, String email, String pword) throws ApiException { if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } String userPassword = email + ":" + pword; String encoding = Base64Coder.encodeString(userPassword); try { URL url = new URL(sUrl); System.setProperty("http.keepAlive", "false"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", "Basic " + encoding); connection.setReadTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setConnectTimeout(REQUEST_TIMEOUT * MILLISECONDS); connection.setRequestProperty("User-Agent", sUserAgent); connection.setRequestMethod("GET"); //Get response code int responseCode = connection.getResponseCode(); if (responseCode != HTTP_STATUS_OK) { throw new ApiException("Invalid response from server: " + connection.getResponseMessage()); } // Pull content stream from response InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } // Return result from buffered stream return new String(content.toByteArray()); } catch (IOException e) { throw new ApiException("Problem communicating with API", e); } }
From source file:com.abid_mujtaba.bitcoin.tracker.network.Client.java
private static String get(String url_string) throws ClientException { HttpURLConnection connection = null; // NOTE: fetchImage is set up to use HTTP not HTTPS try {/* w w w . j a va 2s .co m*/ URL url = new URL(url_string); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); InputStream is = new BufferedInputStream(connection.getInputStream()); int response_code; if ((response_code = connection.getResponseCode()) != 200) { throw new ClientException("Error code returned by response: " + response_code); } return InputStreamToString(is); } catch (SocketTimeoutException e) { throw new ClientException("Socket timed out.", e); } catch (IOException e) { throw new ClientException("IO Exception raised while attempting to GET response.", e); } finally { if (connection != null) { connection.disconnect(); } } }
From source file:com.netflix.raigad.utils.SystemUtils.java
public static String getDataFromUrl(String url) { try {/* w w w . ja v a 2s. c om*/ HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(1000); conn.setReadTimeout(1000); conn.setRequestMethod("GET"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Unable to get data for URL " + url); } byte[] b = new byte[2048]; ByteArrayOutputStream bos = new ByteArrayOutputStream(); DataInputStream d = new DataInputStream((FilterInputStream) conn.getContent()); int c = 0; while ((c = d.read(b, 0, b.length)) != -1) bos.write(b, 0, c); String return_ = new String(bos.toByteArray(), Charsets.UTF_8); logger.info("Calling URL API: {} returns: {}", url, return_); conn.disconnect(); return return_; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:a122016.rr.com.alertme.QueryUtilsPoliceStation.java
/** * Make an HTTP request to the given URL and return a String as the response. *//* w w w. jav a 2 s . 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 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:Main.java
static byte[] httpRequest(String url, byte[] requestBytes, int connectionTimeOutMs, int readTimeOutMs) { byte[] bArr = null; if (!(url == null || requestBytes == null)) { InputStream inputStream = null; HttpURLConnection urlConnection = null; try {//from ww w. j a va 2 s . c om urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoOutput(true); urlConnection.setConnectTimeout(connectionTimeOutMs); urlConnection.setReadTimeout(readTimeOutMs); urlConnection.setFixedLengthStreamingMode(requestBytes.length); OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(requestBytes); outputStream.close(); if (urlConnection.getResponseCode() != 200) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (urlConnection != null) { urlConnection.disconnect(); } } else { inputStream = urlConnection.getInputStream(); ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[16384]; while (true) { int chunkSize = inputStream.read(buffer); if (chunkSize < 0) { break; } else if (chunkSize > 0) { result.write(buffer, 0, chunkSize); } } bArr = result.toByteArray(); if (inputStream != null) { try { inputStream.close(); } catch (IOException e2) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } catch (IOException e3) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e4) { } } if (urlConnection != null) { urlConnection.disconnect(); } } catch (Throwable th) { if (inputStream != null) { try { inputStream.close(); } catch (IOException e5) { } } if (urlConnection != null) { urlConnection.disconnect(); } } } return bArr; }
From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java
/** * ?/* w w w. jav a 2 s . c om*/ * @param postUrl ? * @param param ? * @param method * @return null */ public static String request(String postUrl, String param, String method) { URL url; try { url = new URL(postUrl); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); // ??) conn.setReadTimeout(30000); // ????) conn.setDoOutput(true); // post??http?truefalse conn.setDoInput(true); // ?httpUrlConnectiontrue conn.setUseCaches(false); // Post ? conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestMethod(method);// "POST"GET conn.setRequestProperty("Content-Length", param.length() + ""); String encode = "utf-8"; OutputStreamWriter out = null; out = new OutputStreamWriter(conn.getOutputStream(), encode); out.write(param); out.flush(); if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return null; } // ?? BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = ""; StringBuffer strBuf = new StringBuffer(); while ((line = in.readLine()) != null) { strBuf.append(line).append("\n"); } in.close(); out.close(); return strBuf.toString(); } catch (MalformedURLException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:com.avinashbehera.sabera.network.HttpClient.java
public static JSONObject SendHttpPostUsingUrlConnection(String url, JSONObject jsonObjSend) { URL sendUrl;//from w w w . ja v a 2 s .c o m try { sendUrl = new URL(url); } catch (MalformedURLException e) { Log.d(TAG, "SendHttpPostUsingUrlConnection malformed URL"); return null; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) sendUrl.openConnection(); conn.setReadTimeout(15000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setChunkedStreamingMode(1024); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.addRequestProperty("Content-length", jsonObjSend.toJSONString().length() + ""); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); //writer.write(getPostDataStringfromJsonObject(jsonObjSend)); Log.d(TAG, "jsonobjectSend = " + jsonObjSend.toString()); //writer.write(jsonObjSend.toString()); writer.write(String.valueOf(jsonObjSend)); writer.flush(); writer.close(); os.close(); int responseCode = conn.getResponseCode(); Log.d(TAG, "responseCode = " + responseCode); if (responseCode == HttpsURLConnection.HTTP_OK) { Log.d(TAG, "responseCode = HTTP OK"); InputStream instream = conn.getInputStream(); String resultString = convertStreamToString(instream); instream.close(); Log.d(TAG, "resultString = " + resultString); //resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]" // Transform the String into a JSONObject JSONParser parser = new JSONParser(); JSONObject jsonObjRecv = (JSONObject) parser.parse(resultString); // Raw DEBUG output of our received JSON object: Log.i(TAG, "<JSONObject>\n" + jsonObjRecv.toString() + "\n</JSONObject>"); return jsonObjRecv; } } catch (Exception e) { // More about HTTP exception handling in another tutorial. // For now we just print the stack trace. e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; }
From source file:brainleg.app.util.AppWeb.java
/** * Copied from ITNProxy// ww w. j ava2s . co m */ private static HttpURLConnection doPost(String url, byte[] bytes) throws IOException { HttpURLConnection connection = (HttpURLConnection) HttpConfigurable.getInstance().openConnection(url); connection.setReadTimeout(60 * 1000); connection.setConnectTimeout(10 * 1000); connection.setRequestMethod(HTTP_POST); connection.setDoInput(true); connection.setDoOutput(true); connection.setRequestProperty(HTTP_CONTENT_TYPE, String.format("%s; charset=%s", HTTP_WWW_FORM, ENCODING)); connection.setRequestProperty(HTTP_CONTENT_LENGTH, Integer.toString(bytes.length)); OutputStream out = new BufferedOutputStream(connection.getOutputStream()); try { out.write(bytes); out.flush(); } finally { out.close(); } return connection; }
From source file:a122016.rr.com.alertme.QueryUtils.java
/** * Make an HTTP request to the given URL and return a String as the response. *///from w w w.j av a2s .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 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.dmsl.anyplace.utils.NetworkUtils.java
public static InputStream downloadHttp(String urlS) throws URISyntaxException, IOException { InputStream is = null;/*from w ww.j a v a 2s. c o m*/ URL url = new URL(encodeURL(urlS)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); if (response == 200) { is = conn.getInputStream(); } return is; }