List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:website.openeng.anki.web.HttpFetcher.java
public static String fetchThroughHttp(String address, String encoding) { try {/*from w w w . j av a 2 s. c o m*/ HttpClient httpClient = new DefaultHttpClient(); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 60000); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(address); HttpResponse response = httpClient.execute(httpGet, localContext); if (!response.getStatusLine().toString().contains("OK")) { return "FAILED"; } BufferedReader reader = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), Charset.forName(encoding))); StringBuilder stringBuilder = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { stringBuilder.append(line); } return stringBuilder.toString(); } catch (Exception e) { return "FAILED with exception: " + e.getMessage(); } }
From source file:uk.ac.cam.cl.dtg.picky.client.analytics.Analytics.java
private static void upload(Properties properties, String datasetURL) { if (datasetURL == null) return;//www. j a v a2 s . c om URL url; try { url = new URL(new URL(datasetURL), URL); } catch (MalformedURLException e1) { e1.printStackTrace(); return; } try { HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost post = new HttpPost(url.toURI()); post.setHeader("Content-Type", "text/plain; charset=utf-8"); StringWriter stringWriter = new StringWriter(); properties.store(stringWriter, ""); HttpEntity entity = new StringEntity(stringWriter.toString()); post.setEntity(entity); HttpResponse response = client.execute(post); LOG.info("Uploading analytics: " + response.getStatusLine()); } catch (IOException | URISyntaxException e) { LOG.error(e.getMessage()); } }
From source file:com.android.fastergallery.common.HttpClientFactory.java
/** * Creates an HttpClient with the specified userAgent string. * /* ww w .j ava2 s .c om*/ * @param userAgent * the userAgent string * @return the client */ public static HttpClient newHttpClient(String userAgent) { // AndroidHttpClient is available on all platform releases, // but is hidden until API Level 8 try { Class<?> clazz = Class.forName("android.net.http.AndroidHttpClient"); Method newInstance = clazz.getMethod("newInstance", String.class); Object instance = newInstance.invoke(null, userAgent); HttpClient client = (HttpClient) instance; // ensure we default to HTTP 1.1 HttpParams params = client.getParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); // AndroidHttpClient sets these two parameters thusly by default: // HttpConnectionParams.setSoTimeout(params, 60 * 1000); // HttpConnectionParams.setConnectionTimeout(params, 60 * 1000); // however it doesn't set this one... ConnManagerParams.setTimeout(params, 60 * 1000); return client; } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
From source file:org.wso2.carbon.apimgt.impl.utils.CommonUtil.java
/** * Validate the backend by sending HTTP HEAD * * @param urlVal - backend URL/* ww w . ja v a 2 s . c o m*/ * @return - status of HTTP HEAD Request to backend */ public static String sendHttpHEADRequest(String urlVal) { String response = "error while connecting"; HttpClient client = new DefaultHttpClient(); HttpHead head = new HttpHead(urlVal); client.getParams().setParameter("http.socket.timeout", 4000); client.getParams().setParameter("http.connection.timeout", 4000); if (System.getProperty(APIConstants.HTTP_PROXY_HOST) != null && System.getProperty(APIConstants.HTTP_PROXY_PORT) != null) { if (log.isDebugEnabled()) { log.debug("Proxy configured, hence routing through configured proxy"); } String proxyHost = System.getProperty(APIConstants.HTTP_PROXY_HOST); String proxyPort = System.getProperty(APIConstants.HTTP_PROXY_PORT); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, new Integer(proxyPort))); } try { HttpResponse httpResponse = client.execute(head); int statusCode = httpResponse.getStatusLine().getStatusCode(); //If the endpoint doesn't support HTTP HEAD or if status code is < 400 if (statusCode == 405 || statusCode % 100 < 4) { if (log.isDebugEnabled() && statusCode == 405) { log.debug("Endpoint doesn't support HTTP HEAD"); } response = "success"; } } catch (IOException e) { // sending a default error message. log.error("Error occurred while connecting backend : " + urlVal + ", reason : " + e.getMessage(), e); } finally { client.getConnectionManager().shutdown(); } return response; }
From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java
private static HttpClient getHttpClient() { HttpClient httpClient = new DefaultHttpClient(); final HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, HTTP_REQUEST_TIMEOUT_MS); HttpConnectionParams.setSoTimeout(params, HTTP_REQUEST_TIMEOUT_MS); ConnManagerParams.setTimeout(params, HTTP_REQUEST_TIMEOUT_MS); // return httpClient; return HttpsClientBuilder.getNewHttpClient(params); }
From source file:com.baidu.cafe.local.NetworkUtils.java
/** * download via a url//from w w w . j av a 2 s.co m * * @param url * @param outputStream * openFileOutput("networktester.download", * Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE) */ public static void httpDownload(String url, OutputStream outputStream) { try { HttpClient httpClient = new DefaultHttpClient(); HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); httpClient.execute(new HttpGet(url)).getEntity().writeTo(outputStream); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.bfr.querytools.spectrumbridge.SpectrumBridgeQuery.java
private static HttpClient createClient() { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET); HttpProtocolParams.setUseExpectContinue(params, true); HttpClient client = new DefaultHttpClient(params); HttpConnectionParams.setConnectionTimeout(client.getParams(), 10 * 1000); HttpConnectionParams.setSoTimeout(client.getParams(), 10 * 1000); return client; }
From source file:packjacket.StaticUtils.java
/** * Uploads a file to the PackJacket webserver * @param f the fiel to upload//from w ww . j a v a 2 s . co m * @return the id of the log file, or 0 if it crashed */ public static long uploadLog(File f) { long id = 0; try { //Sets up the HTTP interaction HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost("http://packjacket.sourceforge.net/log/up.php"); //Adds file to a POST MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(f, "image/jpeg"); mpEntity.addPart("uploadedfile", cbFile); //Uplaods file httppost.setEntity(mpEntity); RunnerClass.logger.info("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); //Receives the status message RunnerClass.logger.info("Status: " + response.getStatusLine()); if (resEntity != null) { //Get the id that the server reports String s = EntityUtils.toString(resEntity); RunnerClass.logger.info("Result: " + s); id = Long.parseLong(s.replaceFirst("222 ", "").replace("\n", "")); } if (resEntity != null) resEntity.consumeContent(); //Close connection httpclient.getConnectionManager().shutdown(); } catch (Exception ex) { RunnerClass.logger.info("Internet not available"); } return id; }
From source file:com.fujitsu.dc.client.http.HttpClientFactory.java
/** * This method is used to create a HTTPClient object. * @param type Type of communication// w w w. j a v a 2 s . c o m * @param connectionTimeout Iime-out value (in milliseconds). Use the default value of 0. * @return HttpClient class instance that is created */ @SuppressWarnings("deprecation") public static HttpClient create(final String type, final int connectionTimeout) { if (TYPE_DEFAULT.equalsIgnoreCase(type)) { return new DefaultHttpClient(); } SSLSocketFactory sf = null; Scheme httpScheme = null; Scheme httpsScheme = null; if (TYPE_INSECURE.equalsIgnoreCase(type)) { sf = createInsecureSSLSocketFactory(); httpScheme = new Scheme("https", PORTHTTPS, sf); httpsScheme = new Scheme("http", PORTHTTP, PlainSocketFactory.getSocketFactory()); } else if (TYPE_ANDROID.equalsIgnoreCase(type)) { try { sf = new InsecureSSLSocketFactory(null); } catch (KeyManagementException e) { return null; } catch (UnrecoverableKeyException e) { return null; } catch (NoSuchAlgorithmException e) { return null; } catch (KeyStoreException e) { return null; } httpScheme = new Scheme("https", sf, PORTHTTPS); httpsScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), PORTHTTP); } SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpScheme); schemeRegistry.register(httpsScheme); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = null; if (TYPE_INSECURE.equalsIgnoreCase(type)) { cm = new SingleClientConnManager(schemeRegistry); } else if (TYPE_ANDROID.equalsIgnoreCase(type)) { cm = new SingleClientConnManager(params, schemeRegistry); } HttpClient hc = new DefaultHttpClient(cm, params); HttpParams params2 = hc.getParams(); int timeout = TIMEOUT; if (connectionTimeout != 0) { timeout = connectionTimeout; } // ? /** Connection timed out. */ HttpConnectionParams.setConnectionTimeout(params2, timeout); // ?? /** Time-out of the data acquisition. */ HttpConnectionParams.setSoTimeout(params2, timeout); // ??? /** Do Not redirect. */ HttpClientParams.setRedirecting(params2, false); return hc; }
From source file:grandroid.geo.Geocoder.java
public static List<Address> getFromLocation(Locale locale, double lat, double lng, int maxResult) { String language = locale.getLanguage(); if (locale == Locale.TAIWAN) { language = "zh-TW"; }/*from ww w .j ava 2 s . c o m*/ String address = String.format(locale, "http://maps.googleapis.com/maps/api/geocode/json?latlng=%1$f,%2$f&sensor=false&language=" + language, lat, lng);//locale.getCountry() HttpGet httpGet = new HttpGet(address); HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(AllClientPNames.USER_AGENT, "Mozilla/5.0 (Java) Gecko/20081007 java-geocoder"); //client.getParams().setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 5 * 1000); //client.getParams().setIntParameter(AllClientPNames.SO_TIMEOUT, 25 * 1000); HttpResponse response; List<Address> retList = null; try { response = client.execute(httpGet); HttpEntity entity = response.getEntity(); String json = EntityUtils.toString(entity, "UTF-8"); JSONObject jsonObject = new JSONObject(json); retList = new ArrayList<Address>(); if ("OK".equalsIgnoreCase(jsonObject.getString("status"))) { JSONArray results = jsonObject.getJSONArray("results"); if (results.length() > 0) { for (int i = 0; i < results.length() && i < maxResult; i++) { JSONObject result = results.getJSONObject(i); //Log.e(MyGeocoder.class.getName(), result.toString()); Address addr = new Address(Locale.getDefault()); // addr.setAddressLine(0, result.getString("formatted_address")); JSONArray components = result.getJSONArray("address_components"); String streetNumber = ""; String route = ""; for (int a = 0; a < components.length(); a++) { JSONObject component = components.getJSONObject(a); JSONArray types = component.getJSONArray("types"); for (int j = 0; j < types.length(); j++) { String type = types.getString(j); if (type.equals("locality") || type.equals("administrative_area_level_3")) { addr.setLocality(component.getString("long_name")); } else if (type.equals("street_number")) { streetNumber = component.getString("long_name"); } else if (type.equals("route")) { route = component.getString("long_name"); } else if (type.equals("administrative_area_level_1")) { addr.setAdminArea(component.getString("long_name")); } else if (type.equals("country")) { addr.setCountryName(component.getString("long_name")); addr.setCountryCode(component.getString("short_name")); } } } addr.setAddressLine(0, route + " " + streetNumber); if (result.has("formatted_address")) { addr.setFeatureName(result.getString("formatted_address")); } addr.setLatitude( result.getJSONObject("geometry").getJSONObject("location").getDouble("lat")); addr.setLongitude( result.getJSONObject("geometry").getJSONObject("location").getDouble("lng")); if (addr.getAdminArea() == null) { addr.setAdminArea(""); } retList.add(addr); } } } } catch (ClientProtocolException e) { Log.e("grandroid", "Error calling Google geocode webservice.", e); } catch (IOException e) { Log.e("grandroid", "Error calling Google geocode webservice.", e); } catch (JSONException e) { Log.e("grandroid", "Error parsing Google geocode webservice response.", e); } return retList; }