List of usage examples for java.net HttpURLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.example.socketmobile.android.warrantychecker.network.UserRegistration.java
private Object fetchWarranty(String id, String authString, String query) throws IOException { InputStream is = null;/*w w w . j av a 2 s .co m*/ RegistrationApiResponse result = null; RegistrationApiErrorResponse errorResult = null; String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP); try { URL url = new URL(baseUrl + id + "/registrations"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(10000 /* milliseconds */); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("Authorization", authHeader); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "Warranty query responded: " + response); switch (response / 100) { case 2: is = conn.getInputStream(); RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader(); result = reader.readJsonStream(is); break; case 4: case 5: is = conn.getErrorStream(); RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader(); errorResult = errorReader.readErrorJsonStream(is); break; } } catch (IOException e) { e.printStackTrace(); return null; } finally { if (is != null) { is.close(); } } return (result != null) ? result : errorResult; }
From source file:com.sogrey.sinaweibo.utils.FileUtil.java
/** * ????.//from www. ja va2s .com * * @param url * ? * @return ?? */ public static String getRealFileNameFromUrl(String url) { String name = null; try { if (StrUtil.isEmpty(url)) { return name; } URL mUrl = new URL(url); HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.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", ""); mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive"); mHttpURLConnection.connect(); if (mHttpURLConnection.getResponseCode() == 200) { for (int i = 0;; i++) { String mine = mHttpURLConnection.getHeaderField(i); if (mine == null) { break; } if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) { Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase()); if (m.find()) return m.group(1).replace("\"", ""); } } } } catch (Exception e) { e.printStackTrace(); LogUtil.e(FileUtil.class, "???"); } return name; }
From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java
/** * Make remote request to get all loyalty cards stored in Cozy *//* w ww. j a v a 2s . c om*/ public String getRemoteLoyaltyCards() { URL urlO = null; try { urlO = new URL(designUrl); 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) { EventBus.getDefault() .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored.")); LoyaltyCard.setAllUnsynced(); } else { for (int i = 0; i < jsonArray.length(); i++) { try { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "...")); JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value"); LoyaltyCard loyaltyCard = LoyaltyCard .getByRemoteId(loyaltyCardJson.get("_id").toString()); if (loyaltyCard == null) { loyaltyCard = new LoyaltyCard(loyaltyCardJson); } else { loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id")); loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue")); loyaltyCard.setCode(loyaltyCardJson.getInt("code")); loyaltyCard.setLabel(loyaltyCardJson.getString("label")); loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate")); } loyaltyCard.save(); } catch (JSONException e) { EventBus.getDefault() .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } } else { errorMessage = new JSONObject(result).getString("error"); EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage)); stopSelf(); } in.close(); conn.disconnect(); } catch (MalformedURLException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (JSONException e) { EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } return errorMessage; }
From source file:com.threeti.proxy.RequestFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String path = request.getServletPath(); String pathInfo = path.substring(path.lastIndexOf("/")); if (pathInfo == null) { response.getWriter().write("error"); } else {/* www .ja v a 2 s. c om*/ if (path.contains("/proxy")) { pathInfo = path.substring(path.lastIndexOf("/proxy") + 6); if ("POST".equals(request.getMethod())) { // POST String urlString = this.baseURL + pathInfo; logger.info(urlString); String s = this.getParams(req).substring(0, this.getParams(req).length() - 1); byte[] data = s.getBytes("utf-8"); HttpURLConnection conn = null; DataOutputStream outStream = null; URL httpUrl = new URL(urlString); conn = (HttpURLConnection) httpUrl.openConnection(); conn.setConnectTimeout(7000); conn.setReadTimeout(7000); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "utf-8"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); IOUtils.copy(in, response.getOutputStream()); } else { try { throw new Exception("ResponseCode=" + conn.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } } else if ("DELETE".equals(request.getMethod())) { String urlString = this.baseURL + pathInfo + "?" + this.getParams(req); logger.info(urlString); HttpURLConnection conn = null; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(7000); conn.setReadTimeout(7000); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestMethod("DELETE"); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); IOUtils.copy(in, response.getOutputStream()); } else { try { throw new Exception("ResponseCode=" + conn.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } } else { String urlString = this.baseURL + pathInfo + "?" + this.getParams(req); logger.info(urlString); URL url = new URL(urlString); InputStream input = url.openStream(); IOUtils.copy(input, response.getOutputStream()); } } else { chain.doFilter(req, res); } } }
From source file:net.solarnetwork.node.control.ping.HttpRequesterJob.java
private boolean ping() { log.debug("Attempting to ping {}", url); try {// w ww. j a v a 2 s. co m HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(connectionTimeoutSeconds * 1000); connection.setReadTimeout(connectionTimeoutSeconds * 1000); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); if (sslService != null && connection instanceof HttpsURLConnection) { SSLService service = sslService.service(); if (service != null) { SSLSocketFactory factory = service.getSolarInSocketFactory(); if (factory != null) { HttpsURLConnection sslConnection = (HttpsURLConnection) connection; sslConnection.setSSLSocketFactory(factory); } } } int responseCode = connection.getResponseCode(); return (responseCode >= 200 && responseCode < 400); } catch (IOException e) { log.info("Error pinging {}: {}", url, e.getMessage()); return false; } }
From source file:com.machinelinking.api.client.APIClient.java
private InputStream sendRequest(String service, String group, Map<String, Object> properties) throws IOException { try {/*from w w w.j av a2 s . co m*/ URL url = new URL(service); HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); httpURLConnection.setConnectTimeout(connTimeout); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); properties.put(ParamsValidator.app_id, appId); properties.put(ParamsValidator.app_key, appKey); StringBuilder data = ParamsValidator.getInstance().buildRequest(group, properties); httpURLConnection.addRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); dataOutputStream.write(data.toString().getBytes()); dataOutputStream.close(); if (httpURLConnection.getResponseCode() == 200) { return httpURLConnection.getInputStream(); } else { return httpURLConnection.getErrorStream(); } } catch (MalformedURLException e) { throw new IllegalStateException(e); } }
From source file:cz.incad.kramerius.k5indexer.Commiter.java
/** * Reads data from the data reader and posts it to solr, writes the response * to output//from ww w.ja v a 2 s .co m */ private void postData(URL url, Reader data, String contentType, StringBuilder output) throws Exception { HttpURLConnection urlc = null; try { urlc = (HttpURLConnection) url.openConnection(); urlc.setConnectTimeout(config.getInt("http.timeout", 10000)); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", contentType); OutputStream out = urlc.getOutputStream(); try { Writer writer = new OutputStreamWriter(out, "UTF-8"); pipe(data, writer); writer.close(); } catch (IOException e) { throw new Exception("IOException while posting data", e); } finally { if (out != null) { out.close(); } } InputStream in = urlc.getInputStream(); int status = urlc.getResponseCode(); StringBuilder errorStream = new StringBuilder(); try { if (status != HttpURLConnection.HTTP_OK) { errorStream.append("postData URL=").append(solrUrl).append(" HTTP response code=") .append(status).append(" "); throw new Exception("URL=" + solrUrl + " HTTP response code=" + status); } Reader reader = new InputStreamReader(in); pipeString(reader, output); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (in != null) { in.close(); } } InputStream es = urlc.getErrorStream(); if (es != null) { try { Reader reader = new InputStreamReader(es); pipeString(reader, errorStream); reader.close(); } catch (IOException e) { throw new Exception("IOException while reading response", e); } finally { if (es != null) { es.close(); } } } if (errorStream.length() > 0) { throw new Exception("postData error: " + errorStream.toString()); } } catch (IOException e) { throw new Exception("Solr has throw an error. Check tomcat log. " + e); } finally { if (urlc != null) { urlc.disconnect(); } } }
From source file:com.iflytek.android.framework.volley.toolbox.HurlStack.java
/** * Opens an {@link HttpURLConnection} with parameters. * //from ww w. j a v a 2s .c o m * @param url * @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.mercandalli.android.apps.files.common.net.TaskPost.java
@Override protected String doInBackground(Void... urls) { try {// w ww .java 2 s .co m if (this.mParameters != null) { if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) { mParameters.add(new StringPair("android_id", "" + Config.getNotificationId())); } url = NetUtils.addUrlParameters(url, mParameters); } Log.d("TaskGet", "url = " + url); final URL tmpUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) tmpUrl.openConnection(); conn.setReadTimeout(10_000); conn.setConnectTimeout(15_000); conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken()); conn.setUseCaches(false); conn.setDoInput(true); conn.setDoOutput(true); if (this.mParameters != null) { final OutputStream outputStream = conn.getOutputStream(); final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writer.write(getQuery(mParameters)); writer.flush(); writer.close(); outputStream.close(); } conn.connect(); // Starts the query int responseCode = conn.getResponseCode(); InputStream inputStream = new BufferedInputStream(conn.getInputStream()); // convert inputstream to string String resultString = convertInputStreamToString(inputStream); //int responseCode = response.getStatusLine().getStatusCode(); if (responseCode >= 300) { resultString = "Status Code " + responseCode + ". " + resultString; } conn.disconnect(); return resultString; } catch (IOException e) { Log.e(getClass().getName(), "Failed to convert Json", e); } return null; // try { // // // http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post // // HttpPost httppost = new HttpPost(url); // // MultipartEntity mpEntity = new MultipartEntity(); // if (this.file != null) mpEntity.addPart("file", new FileBody(file, "*/*")); // // String log_parameters = ""; // if (this.parameters != null) // for (StringPair b : parameters) { // mpEntity.addPart(b.getName(), new StringBody(b.getValue(), Charset.forName("UTF-8"))); // log_parameters += b.getName() + ":" + b.getValue() + " "; // } // Log.d("TaskPost", "url = " + url + " " + log_parameters); // // httppost.setEntity(mpEntity); // // StringBuilder authentication = new StringBuilder().append(app.getConfig().getUser().getAccessLogin()).append(":").append(app.getConfig().getUser().getAccessPassword()); // String result = Base64.encodeBytes(authentication.toString().getBytes()); // httppost.setHeader("Authorization", "Basic " + result); // // HttpClient httpclient = new DefaultHttpClient(); // HttpResponse response = httpclient.execute(httppost); // // // receive response as inputStream // InputStream inputStream = response.getEntity().getContent(); // // String resultString = null; // // // convert inputstream to string // if (inputStream != null) // resultString = convertInputStreamToString(inputStream); // // int responseCode = response.getStatusLine().getStatusCode(); // if (responseCode >= 300) // resultString = "Status Code " + responseCode + ". " + resultString; // return resultString; // // // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; }
From source file:jp.go.nict.langrid.servicecontainer.executor.jsonrpc.DynamicJsonRpcServiceExecutor.java
@Override public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable { Map<String, Object> mimeHeaders = new HashMap<String, Object>(); final List<RpcHeader> rpcHeaders = new ArrayList<RpcHeader>(); Pair<Endpoint, Long> r = preprocessJsonRpc(mimeHeaders, rpcHeaders); Endpoint ep = r.getFirst();/* w w w . j ava 2 s . c o m*/ long s = System.currentTimeMillis(); HttpURLConnection con = null; JsonRpcResponse ret = null; RpcFault fault = null; try { con = (HttpURLConnection) ep.getAddress().toURL().openConnection(); con.setUseCaches(false); con.setDoOutput(true); con.setConnectTimeout(3000); con.setReadTimeout(10000); con.setRequestProperty("Accept", "application/json-rpc"); con.setRequestProperty("Content-type", "application/json-rpc"); con.setRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.JSON_RPC); String authUserName = ep.getUserName(); String authPassword = ep.getPassword(); if (authUserName != null && authUserName.length() > 0) { String header = authUserName + ":" + ((authPassword != null) ? authPassword : ""); con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(header.getBytes()))); } for (Map.Entry<String, Object> entry : mimeHeaders.entrySet()) { con.addRequestProperty(entry.getKey(), entry.getValue().toString()); } OutputStream os = con.getOutputStream(); JSON.encode(JsonRpcUtil.createRequest(rpcHeaders, method, args), os); os.flush(); InputStream is = null; try { is = con.getInputStream(); } catch (IOException e) { is = con.getErrorStream(); } finally { if (is != null) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); is = new DuplicatingInputStream(is, baos); try { ret = JSON.decode(is, JsonRpcResponse.class); } catch (JSONException e) { fault = new RpcFault("Server.userException", e.toString(), ExceptionUtil.getMessageWithStackTrace(e) + "\nsource: " + new String(baos.toByteArray(), "UTF-8")); } } else { throw new RuntimeException("failed to open response stream."); } } if (ret.getError() != null) { fault = ret.getError(); throw RpcFaultUtil.rpcFaultToThrowable(ret.getError()); } return converter.convert(ret.getResult(), method.getReturnType()); } finally { long dt = System.currentTimeMillis() - s; List<RpcHeader> resHeaders = null; if (ret != null && ret.getHeaders() != null) { resHeaders = Arrays.asList(ret.getHeaders()); } postprocessJsonRpc(r.getSecond(), dt, con, resHeaders, fault); if (con != null) con.disconnect(); } }