List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:ar.com.aleatoria.ue.rest.SecureSimpleClientHttpRequestFactory.java
/** * Template method for preparing the given {@link HttpURLConnection}. * <p>//w ww . ja v a 2s . c o m * The default implementation prepares the connection for input and output, and sets the HTTP method. * * @param connection the connection to prepare * @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.) * @throws IOException in case of I/O errors */ protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { if (this.connectTimeout >= 0) { connection.setConnectTimeout(this.connectTimeout); } if (this.readTimeout >= 0) { connection.setReadTimeout(this.readTimeout); } connection.setDoInput(true); if ("GET".equals(httpMethod)) { connection.setInstanceFollowRedirects(true); } else { connection.setInstanceFollowRedirects(false); } if ("PUT".equals(httpMethod) || "POST".equals(httpMethod)) { connection.setDoOutput(true); } else { connection.setDoOutput(false); } connection.setRequestMethod(httpMethod); }
From source file:com.example.ronald.tracle.RegistrationIntentService.java
private String downloadContent(String myurl) throws IOException { InputStream is = null;// w w w . java 2 s . c o m int length = 500; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "The response is: " + response); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = convertInputStreamToString(is, length); return contentAsString; } finally { if (is != null) { is.close(); } } }
From source file:eu.codeplumbers.cosi.api.tasks.GetPlacesTask.java
@Override protected List<Place> doInBackground(Void... voids) { URL urlO = null;/* w w w. j av a 2 s . c om*/ try { urlO = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("POST"); // read the response int status = conn.getResponseCode(); InputStream in = null; if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONArray jsonArray = new JSONArray(result); if (jsonArray != null) { if (jsonArray.length() > 0) { for (int i = 0; i < jsonArray.length(); i++) { String version = "0"; if (jsonArray.getJSONObject(i).has("version")) { version = jsonArray.getJSONObject(i).getString("version"); } JSONObject placeJson = jsonArray.getJSONObject(i).getJSONObject("value"); Place place = Place.getByLocation(placeJson.get("description").toString(), placeJson.get("latitude").toString(), placeJson.get("longitude").toString()); if (place == null) { place = new Place(placeJson); } else { place.setDeviceId(placeJson.getString("deviceId")); place.setAddress(placeJson.getString("address")); place.setDateAndTime(placeJson.getString("dateAndTime")); place.setLongitude(placeJson.getDouble("longitude")); place.setLatitude(placeJson.getDouble("latitude")); place.setRemoteId(placeJson.getString("_id")); } publishProgress("Saving place : " + place.getAddress()); place.save(); allPlaces.add(place); } } else { publishProgress("Your Cozy has no places stored."); return allPlaces; } } else { errorMessage = "Failed to parse API response"; } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } return allPlaces; }
From source file:com.epic.framework.implementation.tapjoy.TapjoyURLConnection.java
/** * Gets the file size of the specified resource from the HTTP header field "content-length" * @param url URL of the specified resource. * @return content-length, null otherwise. *//*from ww w. ja v a 2s . c om*/ public String getContentLength(String url) { String contentLength = null; try { String requestURL = url; // Replaces all spaces. requestURL = requestURL.replaceAll(" ", "%20"); TapjoyLog.i(TAPJOY_URL_CONNECTION, "requestURL: " + requestURL); URL httpURL = new URL(requestURL); HttpURLConnection connection = (HttpURLConnection) httpURL.openConnection(); connection.setConnectTimeout(15000); connection.setReadTimeout(30000); contentLength = connection.getHeaderField("content-length"); } catch (Exception e) { TapjoyLog.e(TAPJOY_URL_CONNECTION, "Exception: " + e.toString()); } TapjoyLog.i(TAPJOY_URL_CONNECTION, "content-length: " + contentLength); return contentLength; }
From source file:info.icefilms.icestream.browse.Location.java
protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie, Callback callback) {//from w w w . java2 s . c o m // Declare our buffer ByteArrayBuffer byteArrayBuffer; try { // Setup the connection HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0"); urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString()); if (sendCookie != null) urlConnection.setRequestProperty("Cookie", sendCookie); if (sendData != null) { urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setDoOutput(true); } urlConnection.setConnectTimeout(callback.GetConnectionTimeout()); urlConnection.setReadTimeout(callback.GetConnectionTimeout()); urlConnection.connect(); // Get the output stream and send the data if (sendData != null) { OutputStream outputStream = urlConnection.getOutputStream(); outputStream.write(sendData.getBytes()); outputStream.flush(); outputStream.close(); } // Get the cookie if (getCookie != null) { // Clear the string builder getCookie.delete(0, getCookie.length()); // Loop thru the header fields String headerName; String cookie; for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) { if (headerName.equalsIgnoreCase("Set-Cookie")) { // Get the cookie cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i)); // Add it to the string builder if (cookie != null) getCookie.append(cookie); break; } } } // Get the input stream InputStream inputStream = urlConnection.getInputStream(); // For some reason we can actually get a null InputStream instead of an exception if (inputStream == null) { Log.e("Ice Stream", "Page download failed. Unable to create Input Stream."); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } urlConnection.disconnect(); return null; } // Get the file size final int fileSize = urlConnection.getContentLength(); // Create our buffers byte[] byteBuffer = new byte[2048]; byteArrayBuffer = new ByteArrayBuffer(2048); // Download the page int amountDownloaded = 0; int count; while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) { // Check if we got canceled if (callback.IsCancelled()) { inputStream.close(); urlConnection.disconnect(); return null; } // Add data to the buffer byteArrayBuffer.append(byteBuffer, 0, count); // Update the downloaded amount amountDownloaded += count; } // Close the connection inputStream.close(); urlConnection.disconnect(); // Check for amount downloaded calculation error if (fileSize != -1 && amountDownloaded != fileSize) { Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not " + "match reported content length (" + fileSize + " bytes)."); } } catch (SocketTimeoutException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_timeout_error); } return null; } catch (IOException exception) { Log.e("Ice Stream", "Page download failed.", exception); if (callback.GetErrorBoolean() == false) { callback.SetErrorBoolean(true); callback.SetErrorStringID(R.string.browse_page_download_error); } return null; } // Convert things to a string return new String(byteArrayBuffer.toByteArray()); }
From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java
@Override protected String doInBackground(File... files) { for (int i = 0; i < files.length; i++) { File file = files[i];//from www .jav a2s .c om String binaryRemoteId = file.getRemoteId(); if (!binaryRemoteId.isEmpty()) { publishProgress("Deleting file: " + file.getName(), "0", "100"); URL urlO = null; try { urlO = new URL(url + binaryRemoteId + "/binaries/file"); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("DELETE"); InputStream in = null; // read the response int status = conn.getResponseCode(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { in = conn.getErrorStream(); } else { in = conn.getInputStream(); } StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { errorMessage = conn.getResponseMessage(); } else { errorMessage = deleteFileRequest(file); if (errorMessage == "") { java.io.File newFile = file.getLocalPath(); if (newFile.exists()) { newFile.delete(); } file.delete(); } else { return errorMessage; } } } catch (MalformedURLException e) { errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { errorMessage = e.getLocalizedMessage(); } catch (IOException e) { errorMessage = e.getLocalizedMessage(); } } } return errorMessage; }
From source file:ly.count.android.api.ConnectionProcessor.java
URLConnection urlConnectionForEventData(final String eventData) throws IOException { final String urlStr = serverURL_ + "/i?" + eventData; final URL url = new URL(urlStr); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS); conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS); conn.setUseCaches(false);//from w ww . j av a 2s .c om conn.setDoInput(true); String picturePath = UserData.getPicturePathFromQuery(url); if (Countly.sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Got picturePath: " + picturePath); } if (!picturePath.equals("")) { //Uploading files: //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests File binaryFile = new File(picturePath); conn.setDoOutput(true); // Just generate some unique random value. String boundary = Long.toHexString(System.currentTimeMillis()); // Line separator required by multipart/form-data. String CRLF = "\r\n"; String charset = "UTF-8"; conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())) .append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); FileInputStream fileInputStream = new FileInputStream(binaryFile); byte[] buffer = new byte[1024]; int len; while ((len = fileInputStream.read(buffer)) != -1) { output.write(buffer, 0, len); } output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. fileInputStream.close(); // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); } else { conn.setDoOutput(false); } return conn; }
From source file:com.scut.easyfe.network.kjFrame.http.HttpConnectStack.java
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false);//from w w w . j a v a2 s .c o m connection.setDoInput(true); // use caller-provided custom SslSocketFactory, if any, for HTTPS if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) { ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory); } return connection; }
From source file:cn.leancloud.diamond.server.service.NotifyService.java
/** * http get/* w w w .j av a2 s.co m*/ * * @param urlString * @return */ private String invokeURL(String urlString) { HttpURLConnection conn = null; URL url = null; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); conn.connect(); InputStream urlStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(urlStream)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) reader.close(); } return sb.toString(); } catch (Exception e) { log.error("http,url=" + urlString, e); } finally { if (conn != null) { conn.disconnect(); } } return "error"; }
From source file:com.taobao.diamond.server.service.NotifyService.java
/** * http get/*w w w .ja va 2s.c om*/ * * @param urlString * @return */ private String invokeURL(String urlString) { HttpURLConnection conn = null; URL url = null; try { url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); conn.setRequestMethod("GET"); conn.connect(); InputStream urlStream = conn.getInputStream(); StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(urlStream)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } } finally { if (reader != null) reader.close(); } return sb.toString(); } catch (Exception e) { log.error("http,url=" + urlString, e); } finally { if (conn != null) { conn.disconnect(); } } return "error"; }