List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:org.thialfihar.android.apg.keyimport.HkpKeyserver.java
private String query(String request) throws QueryFailedException, HttpError { InetAddress ips[];/*from www . jav a 2s . c om*/ try { ips = InetAddress.getAllByName(mHost); } catch (UnknownHostException e) { throw new QueryFailedException(e.toString()); } for (int i = 0; i < ips.length; ++i) { try { String url = "http://" + ips[i].getHostAddress() + ":" + mPort + request; Log.d(Constants.TAG, "hkp keyserver query: " + url); URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setConnectTimeout(5000); conn.setReadTimeout(25000); conn.connect(); int response = conn.getResponseCode(); if (response >= 200 && response < 300) { return readAll(conn.getInputStream(), conn.getContentEncoding()); } else { String data = readAll(conn.getErrorStream(), conn.getContentEncoding()); throw new HttpError(response, data); } } catch (MalformedURLException e) { // nothing to do, try next IP } catch (IOException e) { // nothing to do, try next IP } } throw new QueryFailedException("querying server(s) for '" + mHost + "' failed"); }
From source file:com.sogrey.sinaweibo.utils.FileUtil.java
/** * ????.//from ww w . java 2 s .co m * * @param Url * * @return int ? */ public static int getContentLengthFromUrl(String Url) { int mContentLength = 0; try { URL url = new URL(Url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection(); mHttpURLConnection.setConnectTimeout(5 * 1000); mHttpURLConnection.setRequestMethod("GET"); mHttpURLConnection.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*"); mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN"); mHttpURLConnection.setRequestProperty("Referer", Url); mHttpURLConnection.setRequestProperty("Charset", "UTF-8"); mHttpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)"); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { // ???? mContentLength = mHttpURLConnection.getContentLength(); } } catch (Exception e) { e.printStackTrace(); LogUtil.d(FileUtil.class, "?" + e.getMessage()); } return mContentLength; }
From source file:org.digitalcampus.oppia.task.DownloadMediaTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];// w w w .j a v a 2s . com for (Object o : payload.getData()) { Media m = (Media) o; File file = new File(MobileLearning.MEDIA_PATH, m.getFilename()); try { URL u = new URL(m.getDownloadUrl()); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); DownloadProgress dp = new DownloadProgress(); dp.setMessage(m.getFilename()); dp.setProgress(0); publishProgress(dp); FileOutputStream f = new FileOutputStream(file); InputStream in = c.getInputStream(); MessageDigest md = MessageDigest.getInstance("MD5"); in = new DigestInputStream(in, md); byte[] buffer = new byte[8192]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); // check the file digest matches, otherwise delete the file // (it's either been a corrupted download or it's the wrong file) byte[] digest = md.digest(); String resultMD5 = ""; for (int i = 0; i < digest.length; i++) { resultMD5 += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1); } Log.d(TAG, "supplied digest: " + m.getDigest()); Log.d(TAG, "calculated digest: " + resultMD5); if (!resultMD5.contains(m.getDigest())) { this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } else { payload.setResult(true); payload.setResultResponse(ctx.getString(R.string.success_media_download, m.getFilename())); } } catch (ClientProtocolException e1) { e1.printStackTrace(); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (IOException e1) { e1.printStackTrace(); this.deleteFile(file); payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } catch (NoSuchAlgorithmException e) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(e); } else { e.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_media_download)); } } return payload; }
From source file:fyp.project.asyncTask.Http_GetPost.java
public void POST(String url, String val) throws IOException { HttpURLConnection urlConnection = null; try {/*from w w w . j a v a 2 s .com*/ URL url2 = new URL(url); urlConnection = (HttpURLConnection) url2.openConnection(); urlConnection.setRequestMethod("POST"); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(10000); urlConnection.setDoOutput(true); String data = val; OutputStream out = urlConnection.getOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); int responseCode = urlConnection.getResponseCode(); if (responseCode == 200) { InputStream is = urlConnection.getInputStream(); String result = convertInputStreamToString(is); webpage_output = result; } } catch (Exception e) { e.printStackTrace(); } finally { urlConnection.disconnect(); } }
From source file:foam.blob.RestBlobService.java
@Override public Blob put_(X x, Blob blob) { if (blob instanceof IdentifiedBlob) { return blob; }//from w w w .j av a 2 s . c om HttpURLConnection connection = null; OutputStream os = null; InputStream is = null; try { URL url = new URL(address_); connection = (HttpURLConnection) url.openConnection(); //configure HttpURLConnection connection.setConnectTimeout(5 * 1000); connection.setReadTimeout(5 * 1000); connection.setDoOutput(true); connection.setUseCaches(false); //set request method connection.setRequestMethod("PUT"); //configure http header connection.setRequestProperty("Accept", "*/*"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Content-Type", "application/octet-stream"); // get connection ouput stream os = connection.getOutputStream(); //output blob into connection blob.read(os, 0, blob.getSize()); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Upload failed"); } is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); CharBuffer cb = CharBuffer.allocate(65535); reader.read(cb); cb.rewind(); return (Blob) getX().create(JSONParser.class).parseString(cb.toString(), IdentifiedBlob.class); } catch (Throwable t) { t.printStackTrace(); throw new RuntimeException(t); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); IOUtils.close(connection); } }
From source file:com.windigo.http.client.HttpUrlConnectionClient.java
/** * Open http url connection to url and return connection * /* ww w .j a v a 2s .com*/ * @param request * @return {@link HttpURLConnection} * @throws MalformedURLException * @throws IOException */ protected HttpURLConnection openHttpURLConnection(Request request) throws MalformedURLException, IOException { HttpURLConnection connection = (HttpURLConnection) new URL(request.getFullUrl()).openConnection(); connection.setRequestMethod(request.getHttpRequestType().toString()); connection.setConnectTimeout(GlobalSettings.CONNNECTION_TIMEOUT); connection.setReadTimeout(GlobalSettings.CONNECTION_READ_TIMEOUT); Logger.log("[Request] Connection timeout setted to : " + GlobalSettings.CONNNECTION_TIMEOUT); Logger.log("[Request] Connection read timeout setted to : " + GlobalSettings.CONNECTION_READ_TIMEOUT); return connection; }
From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java
private void pingXdServer() { try {/*from w ww . j a v a 2 s. c o m*/ HttpURLConnection con = (HttpURLConnection) new URL(xdServerBaseUrl).openConnection(); con.setRequestMethod("HEAD"); int timeout = 2000; con.setReadTimeout(timeout); con.setConnectTimeout(timeout); int responseCode = con.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { LOG.error("Bad response from server: {} Response: {}", xdServerBaseUrl, responseCode); } } catch (Exception ex) { LOG.error("Could not connect to server: {} Error: {}: {}", xdServerBaseUrl, ex.getClass().getSimpleName(), ex.getMessage()); } }
From source file:com.gargoylesoftware.htmlunit.UrlFetchWebConnection.java
/** * {@inheritDoc}//from w w w.j av a2s . com */ @Override public WebResponse getResponse(final WebRequest webRequest) throws IOException { final long startTime = System.currentTimeMillis(); final URL url = webRequest.getUrl(); if (LOG.isTraceEnabled()) { LOG.trace("about to fetch URL " + url); } // hack for JS, about, and data URLs. final WebResponse response = produceWebResponseForGAEProcolHack(url); if (response != null) { return response; } // this is a "normal" URL try { final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // connection.setUseCaches(false); connection.setConnectTimeout(webClient_.getOptions().getTimeout()); connection.addRequestProperty("User-Agent", webClient_.getBrowserVersion().getUserAgent()); connection.setInstanceFollowRedirects(false); // copy the headers from WebRequestSettings for (final Entry<String, String> header : webRequest.getAdditionalHeaders().entrySet()) { connection.addRequestProperty(header.getKey(), header.getValue()); } addCookies(connection); final HttpMethod httpMethod = webRequest.getHttpMethod(); connection.setRequestMethod(httpMethod.name()); if (HttpMethod.POST == httpMethod || HttpMethod.PUT == httpMethod || HttpMethod.PATCH == httpMethod) { connection.setDoOutput(true); final String charset = webRequest.getCharset(); connection.addRequestProperty("Content-Type", FormEncodingType.URL_ENCODED.getName()); try (final OutputStream outputStream = connection.getOutputStream()) { final List<NameValuePair> pairs = webRequest.getRequestParameters(); final org.apache.http.NameValuePair[] httpClientPairs = NameValuePair.toHttpClient(pairs); final String query = URLEncodedUtils.format(Arrays.asList(httpClientPairs), charset); outputStream.write(query.getBytes(charset)); if (webRequest.getRequestBody() != null) { IOUtils.write(webRequest.getRequestBody().getBytes(charset), outputStream); } } } final int responseCode = connection.getResponseCode(); if (LOG.isTraceEnabled()) { LOG.trace("fetched URL " + url); } final List<NameValuePair> headers = new ArrayList<>(); for (final Map.Entry<String, List<String>> headerEntry : connection.getHeaderFields().entrySet()) { final String headerKey = headerEntry.getKey(); if (headerKey != null) { // map contains entry like (null: "HTTP/1.1 200 OK") final StringBuilder sb = new StringBuilder(); for (final String headerValue : headerEntry.getValue()) { if (sb.length() != 0) { sb.append(", "); } sb.append(headerValue); } headers.add(new NameValuePair(headerKey, sb.toString())); } } final byte[] byteArray; try (final InputStream is = responseCode < 400 ? connection.getInputStream() : connection.getErrorStream()) { byteArray = IOUtils.toByteArray(is); } final long duration = System.currentTimeMillis() - startTime; final WebResponseData responseData = new WebResponseData(byteArray, responseCode, connection.getResponseMessage(), headers); saveCookies(url.getHost(), headers); return new WebResponse(responseData, webRequest, duration); } catch (final IOException e) { LOG.error("Exception while tyring to fetch " + url, e); throw new RuntimeException(e); } }
From source file:eu.vranckaert.worktime.web.json.JsonWebServiceImpl.java
@Override public boolean isEndpointAvailable(String endpoint) { try {// ww w. j a va 2 s . c o m URL url = new URL(endpoint); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(3000); urlc.connect(); if (urlc.getResponseCode() == HttpStatusCode.OK) { return true; } } catch (MalformedURLException e1) { } catch (IOException e) { } return false; }
From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java
public void sendChangesToCozy() { List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced(); int i = 0;//from w w w . j ava2s .co m for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) { URL urlO = null; try { JSONObject jsonObject = loyaltyCard.toJsonObject(); mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false); mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":"); mNotifyManager.notify(notification_id, mBuilder.build()); EventBus.getDefault().post( new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone))); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(syncUrl); requestMethod = "POST"; } else { urlO = new URL(syncUrl + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); long objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); loyaltyCard.setRemoteId(result); loyaltyCard.save(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); e.printStackTrace(); stopSelf(); } i++; } }