List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:fr.haploid.webservices.WebServicesTask.java
@Override protected JSONObject doInBackground(Void... params) { try {/*from ww w . jav a 2s .com*/ if (mSendCacheResult) { JSONObject cacheResultMessage = new JSONObject(); cacheResultMessage.put(Cobalt.kJSType, Cobalt.JSTypePlugin); cacheResultMessage.put(Cobalt.kJSPluginName, JSPluginNameWebservices); JSONObject storedData = new JSONObject(); storedData.put(kJSCallId, mCallId); cacheResultMessage.put(Cobalt.kJSData, storedData); int storageSize = WebServicesData.getCountItem(); if (storageSize > 0) { if (mStorageKey != null) { String storedValue = WebServicesPlugin.storedValueForKey(mStorageKey, mFragment); if (storedValue != null) { try { storedData.put(Cobalt.kJSData, WebServicesPlugin .treatData(new JSONObject(storedValue), mProcessData, mFragment)); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageResult); //cacheResultMessage.put(Cobalt.kJSData, storedData); } catch (JSONException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: value parsing failed for key " + mStorageKey + ". Value: " + storedValue); exception.printStackTrace(); } cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextUnknownError); } } else { if (Cobalt.DEBUG) Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: value not found in cache for key " + mStorageKey + "."); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextNotFound); } } else { cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextUnknownError); } } else { if (Cobalt.DEBUG) Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: cache is empty."); cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError); storedData.put(kJSText, JSTextEmpty); } cacheResultMessage.put(Cobalt.kJSData, storedData); mFragment.sendMessage(cacheResultMessage); } if (mUrl != null && mType != null) { // TODO: later, use Helper /* responseData = WebServicesHelper.downloadFromServer(data.getString(URL), data.getJSONObject(PARAMS), data.getString(TYPE)); if (responseData != null) { responseHolder.put(TEXT, responseData.getResponseData()); responseHolder.put(STATUS_CODE, responseData.getStatusCode()); responseHolder.put(WS_SUCCESS, responseData.isSuccess()); responseHolder.put(CALL_WS, true); } */ Uri.Builder builder = new Uri.Builder(); builder.encodedPath(mUrl); if (!mParams.equals("") && mType.equalsIgnoreCase(JSTypeGET)) builder.encodedQuery(mParams); JSONObject response = new JSONObject(); response.put(kJSSuccess, false); try { URL url = new URL(builder.build().toString()); try { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); if (mTimeout > 0) urlConnection.setConnectTimeout(mTimeout); urlConnection.setRequestMethod(mType); urlConnection.setDoInput(true); if (mHeaders != null) { JSONArray names = mHeaders.names(); if (names != null) { int length = names.length(); for (int i = 0; i < length; i++) { String name = names.getString(i); urlConnection.setRequestProperty(name, mHeaders.get(name).toString()); } } } if (!mParams.equals("") && !mType.equalsIgnoreCase(JSTypeGET)) { urlConnection.setDoOutput(true); OutputStream outputStream = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(outputStream, "UTF-8")); writer.write(mParams); writer.flush(); writer.close(); outputStream.close(); } urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); if (responseCode != -1) { response.put(kJSStatusCode, responseCode); if (responseCode < 400) response.put(kJSSuccess, true); } try { InputStream inputStream; if (responseCode >= 400 && responseCode < 600) inputStream = urlConnection.getErrorStream(); else inputStream = urlConnection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuffer buffer = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { buffer.append(line).append("\n"); } if (buffer.length() != 0) response.put(kJSText, buffer.toString()); } catch (IOException exception) { if (Cobalt.DEBUG) { Log.i(WebServicesPlugin.TAG, TAG + " - doInBackground: no DATA returned by server."); exception.printStackTrace(); } } } catch (ProtocolException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: not supported request method type " + mType); exception.printStackTrace(); } } catch (IOException exception) { exception.printStackTrace(); } return response; } catch (MalformedURLException exception) { if (Cobalt.DEBUG) { Log.e(WebServicesPlugin.TAG, TAG + " - doInBackground: malformed url " + builder.build().toString() + "."); exception.printStackTrace(); } } } } catch (JSONException exception) { exception.printStackTrace(); } return null; }
From source file:com.vibeosys.utils.dbdownloadv1.DbDownload.java
public String downloadDatabase() { boolean flag = false; HttpURLConnection urlConnection = null; OutputStream myOutput = null; byte[] buffer = null; InputStream inputStream = null; String message = FAIL;//from www. j a v a2 s . co m System.out.print(downloadDBURL); try { URL url = new URL(downloadDBURL); urlConnection = (HttpURLConnection) url.openConnection(); System.out.println("##Request Sent..."); urlConnection.setDoOutput(true); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(20000); urlConnection.setReadTimeout(10000); urlConnection.connect(); int Http_Result = urlConnection.getResponseCode(); String res = urlConnection.getResponseMessage(); System.out.println(res); System.out.println(String.valueOf(Http_Result)); if (Http_Result == HttpURLConnection.HTTP_OK) { String contentType = urlConnection.getContentType(); inputStream = urlConnection.getInputStream(); System.out.println(contentType); if (contentType.equals("application/octet-stream")) { buffer = new byte[1024]; myOutput = new FileOutputStream(this.dbFile); int length; while ((length = inputStream.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); inputStream.close(); flag = true; message = SUCCESS; } else if (contentType.equals("application/json; charset=UTF-8")) { message = FAIL; flag = false; String responce = convertStreamToString(inputStream); System.out.println(responce); try { JSONObject jsResponce = new JSONObject(responce); message = jsResponce.getString("message"); } catch (JSONException e) { // addError(screenName, "Json error in downloadDatabase", e.getMessage()); System.out.println(e.toString()); } } } } catch (Exception ex) { System.out.println("##ROrder while downloading database" + ex.toString()); //addError(screenName, "downloadDatabase", ex.getMessage()); } return message; }
From source file:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {//from w w w.j a v a 2 s. c o m URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:com.adaptris.core.http.JdkHttpProducer.java
@Override protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination destination, long timeout) throws ProduceException { AdaptrisMessage reply = defaultIfNull(getMessageFactory()).newMessage(); ThreadLocalCredentials threadLocalCreds = null; try {/* w ww .ja v a 2 s . c o m*/ URL url = new URL(destination.getDestination(msg)); if (getPasswordAuthentication() != null) { Authenticator.setDefault(AdapterResourceAuthenticator.getInstance()); threadLocalCreds = ThreadLocalCredentials.getInstance(url.toString()); threadLocalCreds.setThreadCredentials(getPasswordAuthentication()); AdapterResourceAuthenticator.getInstance().addAuthenticator(threadLocalCreds); } HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setRequestMethod(methodToUse(msg).name()); http.setInstanceFollowRedirects(handleRedirection()); http.setDoInput(true); http.setConnectTimeout(Long.valueOf(timeout).intValue()); http.setReadTimeout(Long.valueOf(timeout).intValue()); // ProxyUtil.applyBasicProxyAuthorisation(http); addHeaders(msg, http); if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) { http.setRequestProperty(CONTENT_TYPE, msg.getMetadataValue(getContentTypeKey())); } // if (getAuthorisation() != null) { // http.setRequestProperty(AUTHORIZATION, getAuthorisation()); // } // logHeaders("Request Information", "Request Method : " + http.getRequestMethod(), http.getRequestProperties().entrySet()); sendMessage(msg, http); readResponse(http, reply); // logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet()); } catch (IOException e) { throw new ProduceException(e); } catch (CoreException e) { if (e instanceof ProduceException) { throw (ProduceException) e; } else { throw new ProduceException(e); } } finally { if (threadLocalCreds != null) { threadLocalCreds.removeThreadCredentials(); AdapterResourceAuthenticator.getInstance().removeAuthenticator(threadLocalCreds); } } return reply; }
From source file:org.elasticsearch.metrics.ElasticsearchReporter.java
/** * Open a new HttpUrlConnection, in case it fails it tries for the next host in the configured list *//*from ww w .j av a2s . c om*/ private HttpURLConnection openConnection(String uri, String method) { for (String host : hosts) { try { URL templateUrl = new URL("http://" + host + uri); HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection(); connection.setRequestMethod(method); connection.setConnectTimeout(timeout); connection.setUseCaches(false); if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } connection.connect(); return connection; } catch (IOException e) { LOGGER.error("Error connecting to {}: {}", host, e); } } return null; }
From source file:com.oneops.metrics.es.ElasticsearchReporter.java
/** * Open a new HttpUrlConnection, in case it fails it tries for the next host in the configured list * We use search fqdn , if the exception is there we will retry ). Now just using a fixed sleep * //TODO add a more generic support for hosts array* *//*w w w .ja va 2 s . c o m*/ private HttpURLConnection openConnection(String uri, String method) { for (int j = 0; j < ES_CONNECT_RETRIES; ++j) try { URL templateUrl = new URL("http://" + hosts[0] + uri); HttpURLConnection connection = (HttpURLConnection) templateUrl.openConnection(); connection.setRequestMethod(method); connection.setConnectTimeout(timeout); connection.setUseCaches(false); if (method.equalsIgnoreCase("POST") || method.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } connection.connect(); return connection; } catch (IOException e) { try { TimeUnit.MILLISECONDS.sleep(SLEEP_BEFORE_RETRY_IN_MILLIS); } catch (InterruptedException e1) { Thread.currentThread().interrupt(); } LOGGER.error( "Error connecting to {}: {}; " + (j + 1) + " Attempt failed of " + ES_CONNECT_RETRIES, hosts[0], e); } return null; }
From source file:com.mingsoft.weixin.util.UploadDownUtils.java
/** * ? /*from w ww . j av a 2 s .c o m*/ * * @return */ public String downMedia(String msgType, String media_id, String path) { String localFile = null; // SimpleDateFormat df = new SimpleDateFormat("/yyyyMM/"); try { String url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=" + getAccessToken() + "&media_id=" + media_id; // log.error(path); // ? ? URL urlObj = new URL(url); HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); String xx = conn.getHeaderField("Content-disposition"); try { log.debug("===? +==?==" + xx); if (xx == null) { InputStream in = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf-8")); String line = null; String result = null; while ((line = reader.readLine()) != null) { if (result == null) { result = line; } else { result += line; } } System.out.println(result); JSONObject dataJson = JSONObject.parseObject(result); return dataJson.getString("errcode"); } } catch (Exception e) { } if (conn.getResponseCode() == 200) { String Content_disposition = conn.getHeaderField("Content-disposition"); InputStream inputStream = conn.getInputStream(); // // ? // Long fileSize = conn.getContentLengthLong(); // + String savePath = path + "/" + msgType; // ?? String fileName = StringUtil.getDateSimpleStr() + Content_disposition.substring(Content_disposition.lastIndexOf(".")).replace("\"", ""); // File saveDirFile = new File(savePath); if (!saveDirFile.exists()) { saveDirFile.mkdirs(); } // ?? if (!saveDirFile.canWrite()) { log.error("??"); throw new Exception(); } // System.out.println("------------------------------------------------"); // ? File file = new File(saveDirFile + "/" + fileName); FileOutputStream outStream = new FileOutputStream(file); int len = -1; byte[] b = new byte[1024]; while ((len = inputStream.read(b)) != -1) { outStream.write(b, 0, len); } outStream.flush(); outStream.close(); inputStream.close(); // ? localFile = fileName; } } catch (Exception e) { log.error("? !", e); } finally { } return localFile; }
From source file:com.conx.logistics.kernel.bpm.impl.jbpm.core.mock.BPMGuvnorUtil.java
public boolean canBuildPackage(String packageName) { try {//from w ww.j av a 2s.c o m String packagesBinaryURL = getGuvnorProtocol() + "://" + getGuvnorHost() + "/" + getGuvnorSubdomain() + "/rest/packages/" + packageName + "/binary"; URL checkURL = new URL(packagesBinaryURL); HttpURLConnection checkConnection = (HttpURLConnection) checkURL.openConnection(); checkConnection.setRequestMethod("GET"); checkConnection.setConnectTimeout(Integer.parseInt(getGuvnorConnectTimeout())); checkConnection.setReadTimeout(Integer.parseInt(getGuvnorReadTimeout())); applyAuth(checkConnection); checkConnection.connect(); return checkConnection.getResponseCode() == 200; } catch (Exception e) { return false; } }