List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.youTransactor.uCube.mdm.MDMManager.java
public HttpURLConnection initRequest(String service, String method) throws IOException { URL url = new URL(serverURL + WS_URL_PREFIX + service); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (urlConnection instanceof HttpsURLConnection) { ((HttpsURLConnection) urlConnection).setSSLSocketFactory(sslContext.getSocketFactory()); }//from w ww.ja v a2 s. co m urlConnection.setRequestMethod(method); urlConnection.setConnectTimeout(20000); urlConnection.setReadTimeout(30000); LogManager.debug(MDMManager.class.getSimpleName(), "init request: " + url.getPath() + " (" + method + ")"); return urlConnection; }
From source file:com.wareninja.android.commonutils.foursquareV2.http.AbstractHttpApi.java
public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary) throws IOException { //-WareNinjaUtils.trustEveryone();//YG HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoInput(true);//ww w . j a va2s.com conn.setDoOutput(true); conn.setUseCaches(false); conn.setConnectTimeout(TIMEOUT * 1000); conn.setRequestMethod("POST"); conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); return conn; }
From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java
private HttpURLConnection createHTTPConnection(String payload) throws IOException { LOGGER.debug("{} - Message: {}", instanceName, payload); HttpURLConnection conn; conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);// w w w . j av a2 s. c o m conn.setRequestMethod("POST"); conn.setConnectTimeout(connectionTimeout); conn.setRequestProperty("Content-Length", "" + Integer.toString(payload.getBytes().length)); conn.setRequestProperty("User-Agent", "bischeck"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml"); conn.setRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8"); return conn; }
From source file:com.spotify.helios.client.DefaultHttpConnector.java
private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity, final Map<String, List<String>> headers, final String endpointHost) throws IOException { if (log.isTraceEnabled()) { log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(), Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length, Json.asPrettyStringUnchecked(entity)); } else {/*from w w w . j a v a 2 s . c o m*/ log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length); } final HttpURLConnection connection = (HttpURLConnection) ipUri.toURL().openConnection(); handleHttps(connection, endpointHost, hostnameVerifierProvider, extraHttpsHandler); connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setInstanceFollowRedirects(false); connection.setConnectTimeout(httpTimeoutMillis); connection.setReadTimeout(httpTimeoutMillis); for (Map.Entry<String, List<String>> header : headers.entrySet()) { for (final String value : header.getValue()) { connection.addRequestProperty(header.getKey(), value); } } if (entity.length > 0) { connection.setDoOutput(true); connection.getOutputStream().write(entity); } setRequestMethod(connection, method, connection instanceof HttpsURLConnection); return connection; }
From source file:eu.codeplumbers.cosi.services.CosiFileService.java
private void getAllRemoteFiles() { URL urlO = null;//ww w . j av a2s . c om try { urlO = new URL(fileUrl); 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) { for (int i = 0; i < jsonArray.length(); i++) { JSONObject fileJson = jsonArray.getJSONObject(i).getJSONObject("value"); File file = File.getByRemoteId(fileJson.get("_id").toString()); if (file == null) { file = new File(fileJson, false); } else { file.setName(fileJson.getString("name")); file.setPath(fileJson.getString("path")); file.setCreationDate(fileJson.getString("creationDate")); file.setLastModification(fileJson.getString("lastModification")); file.setTags(fileJson.getString("tags")); if (fileJson.has("binary")) { file.setBinary(fileJson.getJSONObject("binary").toString()); } file.setIsFile(true); file.setFileClass(fileJson.getString("class")); file.setMimeType(fileJson.getString("mime")); file.setSize(fileJson.getLong("size")); } mBuilder.setProgress(jsonArray.length(), i, false); mBuilder.setContentText("Indexing file : " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault() .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing file : " + file.getName())); file.setDownloaded(FileUtils.checkFileExists(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName())); file.save(); allFiles.add(file); } } else { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, new JSONObject(result).getString("error"))); mNotifyManager.notify(notification_id, mBuilder.build()); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { e.printStackTrace(); EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } }
From source file:edu.hackathon.perseus.core.httpSpeedTest.java
public double testDownload() { double bw = 0.0; try {//from www. j a v a2 s . co m Date oldTime = new Date(); URL obj = new URL(amazonDomain + "/download_test.bin"); HttpURLConnection httpGetCon = (HttpURLConnection) obj.openConnection(); // optional default is GET httpGetCon.setRequestMethod("GET"); httpGetCon.setConnectTimeout(5000); //set timeout to 5 seconds httpGetCon.setReadTimeout(5000); //add request header httpGetCon.setRequestProperty("User-Agent", USER_AGENT); if (httpGetCon.getResponseCode() == 200) { Date newTime = new Date(); double milliseconds = newTime.getTime() - oldTime.getTime(); int lenght = httpGetCon.getContentLength(); bw = ((double) lenght * 8) / (milliseconds * (double) 1000); } // BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); // String inputLine; // StringBuffer response = new StringBuffer(); // while ((inputLine = in.readLine()) != null) { // response.append(inputLine); // } // in.close(); // // //print result // System.out.println(response.toString()); } catch (MalformedURLException e) { System.out.println("MalformedURLException is fired!"); } catch (IOException e) { System.out.println("Exception is fired in download test. error:" + e.getMessage()); } return bw; }
From source file:com.android.volley.toolbox.http.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * * @param url//from w w w.ja v a2 s . c o m * @return an open connection * @throws IOException */ private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException { HttpURLConnection connection = createConnection(url); int timeoutMs = request.getTimeoutMs(); connection.setConnectTimeout(timeoutMs); connection.setReadTimeout(timeoutMs); connection.setUseCaches(false); 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:com.adaptris.core.http.client.net.StandardHttpProducer.java
private HttpURLConnection configureTimeouts(HttpURLConnection http, long timeout) { if (getConnectTimeout() != null) { http.setConnectTimeout(Long.valueOf(getConnectTimeout().toMilliseconds()).intValue()); }/*from w w w.j av a 2 s. c o m*/ if (getReadTimeout() != null) { http.setReadTimeout(Long.valueOf(getReadTimeout().toMilliseconds()).intValue()); } if (timeout != DEFAULT_TIMEOUT) { http.setReadTimeout(Long.valueOf(timeout).intValue()); } return http; }
From source file:com.jaredrummler.android.device.DeviceName.java
/** Download URL to String */ private static String downloadJson(String myurl) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = null; try {//from ww w.j a va2 s .c o m URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } return sb.toString(); } finally { if (reader != null) { reader.close(); } } }
From source file:moodle.android.moodle.helpers.MoodleWebService.java
private JSONObject getWebServiceResponse(String serverurl, String functionName, String urlParameters, int xslRawId) { JSONObject jsonobj = null;/*w ww . jav a 2s . c om*/ try { HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName).openConnection(); //HttpURLConnection con = (HttpURLConnection) new URL(serverurl + functionName + "&moodlewsrestformat=json").openConnection(); con.setConnectTimeout(30000); con.setReadTimeout(30000); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestProperty("Content-Language", "en-US"); con.setDoOutput(true); con.setUseCaches(false); con.setDoInput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); Log.d("URLParameters: ", urlParameters.toString()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); //Get Response InputStream is = con.getInputStream(); Source xmlSource = new StreamSource(is); Source xsltSource = new StreamSource(context.getResources().openRawResource(xslRawId)); TransformerFactory transFact = TransformerFactory.newInstance(); Transformer trans = transFact.newTransformer(xsltSource); StringWriter writer = new StringWriter(); trans.transform(xmlSource, new StreamResult(writer)); String jsonstr = writer.toString(); jsonstr = jsonstr.replace("<div class=\"no-overflow\"><p>", ""); jsonstr = jsonstr.replace("</p></div>", ""); jsonstr = jsonstr.replace("<p>", ""); jsonstr = jsonstr.replace("</p>", ""); Log.d("TransformObject: ", jsonstr); jsonobj = new JSONObject(jsonstr); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonobj; }