List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:ti.modules.titanium.geolocation.TiLocation.java
private AsyncTask<Object, Void, Integer> getLookUpTask() { AsyncTask<Object, Void, Integer> task = new AsyncTask<Object, Void, Integer>() { @Override//from ww w . j a v a 2 s. co m protected Integer doInBackground(Object... args) { GeocodeResponseHandler geocodeResponseHandler = null; KrollDict event = null; try { String url = (String) args[0]; String direction = (String) args[1]; geocodeResponseHandler = (GeocodeResponseHandler) args[2]; Log.d(TAG, "GEO URL [" + url + "]", Log.DEBUG_MODE); HttpGet httpGet = new HttpGet(url); HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpClient client = new DefaultHttpClient(httpParams); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = client.execute(httpGet, responseHandler); Log.i(TAG, "received Geo [" + response + "]", Log.DEBUG_MODE); if (response != null) { try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean(TiC.PROPERTY_SUCCESS)) { if (direction.equals("forward")) { event = buildForwardGeocodeResponse(jsonObject); } else { event = buildReverseGeocodeResponse(jsonObject); } event.putCodeAndMessage(TiC.ERROR_CODE_NO_ERROR, null); } else { event = new KrollDict(); String errorCode = "Unable to resolve message: Code (" + jsonObject.getString(TiC.ERROR_PROPERTY_ERRORCODE) + ")"; event.putCodeAndMessage(TiC.ERROR_CODE_UNKNOWN, errorCode); } } catch (JSONException e) { Log.e(TAG, "Error converting geo response to JSONObject [" + e.getMessage() + "]", e, Log.DEBUG_MODE); } } } catch (Throwable t) { Log.e(TAG, "Error retrieving geocode information [" + t.getMessage() + "]", t, Log.DEBUG_MODE); } if (geocodeResponseHandler != null) { if (event == null) { event = new KrollDict(); event.putCodeAndMessage(TiC.ERROR_CODE_UNKNOWN, "Error obtaining geolocation"); } geocodeResponseHandler.handleGeocodeResponse(event); } return -1; } }; return task; }
From source file:com.cianmcgovern.android.ShopAndShare.Share.java
/** * Uploads the text file specified by filename * //from w w w.j a va2 s.c o m * @param instance * The results instance to use * @param location * The location as specified by the user * @param store * The store as specified by the user * @return Response message from server * @throws ClientProtocolException * @throws IOException */ private String upload(Results instance, String location, String store) throws ClientProtocolException, IOException { Log.v(Constants.LOG_TAG, "Inside upload"); HttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String filename = Results.getInstance().toFile(); HttpPost httpPost = new HttpPost(Constants.FULL_URL); File file = new File(filename); MultipartEntity entity = new MultipartEntity(); ContentBody cb = new FileBody(file, "plain/text"); entity.addPart("inputfile", cb); ContentBody cbLocation = new StringBody(location); entity.addPart("location", cbLocation); ContentBody cbStore = new StringBody(store); entity.addPart("store", cbStore); httpPost.setEntity(entity); Log.v(Constants.LOG_TAG, "Sending post"); HttpResponse response = httpClient.execute(httpPost); HttpEntity resEntity = response.getEntity(); String message = EntityUtils.toString(resEntity); Log.v(Constants.LOG_TAG, "Response from upload is: " + message); resEntity.consumeContent(); httpClient.getConnectionManager().shutdown(); file.delete(); return message; }
From source file:pl.openrnd.connection.rest.ConnectionHandler.java
private HttpResponse execute(HttpUriRequest request, Integer connectionTimeout, Integer readTimeout) throws ClientProtocolException, IOException { HttpResponse response = null;//from w w w .j a va 2s. co m HttpClient httpClient = getHttpClient(); HttpParams params = httpClient.getParams(); Integer connectionTimeoutOriginal = null; Integer readTimeoutOriginal = null; if (connectionTimeout != null) { connectionTimeoutOriginal = HttpConnectionParams.getConnectionTimeout(params); HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); } if (readTimeout != null) { readTimeoutOriginal = HttpConnectionParams.getSoTimeout(params); HttpConnectionParams.setSoTimeout(params, readTimeout); } try { if (mConnectionConfig.isUsingCookies()) { createCookieIfNotSet(); response = httpClient.execute(request, getHttpContext()); } else { response = httpClient.execute(request); } } finally { if (connectionTimeoutOriginal != null) { HttpConnectionParams.setConnectionTimeout(params, connectionTimeout); } if (readTimeoutOriginal != null) { HttpConnectionParams.setSoTimeout(params, readTimeoutOriginal); } } return response; }
From source file:wsattacker.plugin.dos.dosExtension.requestSender.Http4RequestSenderImpl.java
public String sendRequestHttpClient(RequestObject requestObject) { String strUrl = requestObject.getEndpoint(); String strXml = requestObject.getXmlMessage(); byte[] compressedXml = requestObject.getCompressedXML(); StringBuffer result = new StringBuffer(); try {/*from w w w . jav a 2 s . c o m*/ HttpClient client = new DefaultHttpClient(); setParamsToClient(client); if (useProxy) { HttpHost proxy = new HttpHost("sbrproxy1.eur.ad.sag", 3103); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } HttpPost post = new HttpPost(strUrl); setHeader(requestObject, post); ByteArrayEntity entity; if (compressedXml != null) { entity = new ByteArrayEntity(compressedXml) { @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(outstream); sendLastByte = System.nanoTime(); } }; } else { entity = new ByteArrayEntity(strXml.getBytes("UTF-8")) { @Override public void writeTo(OutputStream outstream) throws IOException { super.writeTo(outstream); sendLastByte = System.nanoTime(); } }; } post.setEntity(entity); HttpResponse response = client.execute(post); receiveFirstByte = System.nanoTime(); BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } } catch (NumberFormatException e) { } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // if (!result.toString().contains("tema tis rolod muspi meroL")) { // System.out.println(result); // } return result.toString(); }
From source file:hornet.framework.technical.HTTPClientParameterBuilderTest.java
/** * Test load http param to http client from config. *//*w w w .j a va 2s . c o m*/ @Test public void testLoadHttpParamToHttpClientFromConfig() { final HttpClient httpClient = new DefaultHttpClient(); HTTPClientParameterBuilder.loadHttpParamToHttpClientFromConfig(httpClient, "http-parameters"); assertEquals("mozilla", httpClient.getParams().getParameter("http.useragent")); }
From source file:hornet.framework.technical.HTTPClientParameterBuilderTest.java
/** * Teste la mthode <tt>loadHttpParamToHttpClientFromConfig</tt> pour le cas o le paramtrage par dfaut * est dfini./*from w w w. ja v a 2 s.c o m*/ */ @SuppressWarnings("unchecked") @Test public void testLoadHttpParamToHttpClientShouldLoadDefaultValue() { final HttpClient httpClient = new DefaultHttpClient(); HTTPClientParameterBuilder.loadHttpParamToHttpClientFromConfig(httpClient, null); final HttpParams httpParams = httpClient.getParams(); assertEquals(CONST_3000, httpParams.getIntParameter("http.connection.timeout", 0)); final Map<HttpHost, Integer> maxPerHost = (Map<HttpHost, Integer>) httpParams .getParameter("http.connection-manager.max-per-host"); assertEquals(1, maxPerHost.size()); assertTrue(maxPerHost.containsKey(new HttpHost("hostname"))); assertEquals(Integer.valueOf(CONST_50), maxPerHost.get(new HttpHost("hostname"))); assertEquals(CONST_50, httpParams.getIntParameter("http.connection-manager.max-total", 0)); assertEquals(CONST_3000, httpParams.getLongParameter("http.connection-manager.timeout", 0)); assertEquals(CONST_60000, httpParams.getIntParameter("http.socket.timeout", 0)); assertEquals(org.apache.http.impl.conn.PoolingHttpClientConnectionManager.class, httpParams.getParameter("http.connection-manager.class")); }
From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.FreeboxDownloaderService.java
private String loginFreebox(String password) throws UnsupportedEncodingException, ClientProtocolException, IOException { String cookieFbx = ""; String csrfToken = ""; // Prparation des paramtres HttpPost postReq = new HttpPost(urlFreebox + "/login.php"); List<NameValuePair> parametres = new ArrayList<NameValuePair>(); parametres.add(new BasicNameValuePair("login", "freebox")); parametres.add(new BasicNameValuePair("passwd", password)); postReq.setEntity(new UrlEncodedFormEntity(parametres)); // Envoi de la requte HttpParams httpParameters = new BasicHttpParams(); // Mise en place de timeouts int timeoutConnection = 5000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpParams params = httpclient.getParams(); HttpClientParams.setRedirecting(params, false); HttpResponse response = httpclient.execute(postReq); // Ok ? (302 = moved = redirection) if (response.getStatusLine().getStatusCode() == 302) { Header cookie = response.getFirstHeader("Set-Cookie"); cookieFbx = cookie.getValue();//ww w. ja va 2s . c o m // Extraction du cookie FBXSID cookieFbx = cookieFbx.substring(cookieFbx.indexOf("FBXSID=\""), cookieFbx.indexOf("\";") + 1); Log.d(TAG, "Cookie = " + cookieFbx); } else { Log.d(TAG, "Erreur d'authentification - statusCode = " + response.getStatusLine().getStatusCode() + " - reason = " + response.getStatusLine().getReasonPhrase()); prepareAlertDialog("Erreur d'authentification"); } // On a le cookie, il nous manque le csrf_token // On rcupre la page download ! HttpGet downloadPageReq = new HttpGet(urlFreebox + "/download.php"); downloadPageReq.setHeader("Cookie", "FBXSID=\"" + cookieFbx + "\";"); response = httpclient.execute(downloadPageReq); // Ok ? if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); InputStream contentStream = entity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(contentStream)); String line = br.readLine(); while (line != null) { if (line.contains("input type=\"hidden\" name=\"csrf_token\"")) { csrfToken = line.substring(line.indexOf("value=\"") + "value=\"".length(), line.lastIndexOf("\"")); break; } line = br.readLine(); } br.close(); contentStream.close(); Log.d(TAG, "csrfToken = " + csrfToken); } else { Log.d(TAG, "Erreur d'authentification - statusCode = " + response.getStatusLine().getStatusCode() + " - reason = " + response.getStatusLine().getReasonPhrase()); prepareAlertDialog("Erreur d'authentification"); } // C'est moche, mais a me permet de corriger a vite fait... return cookieFbx + "<-->" + csrfToken; }
From source file:com.pansapiens.occyd.UrlFetch.java
public void fetch() { String response = ""; Message msg = Message.obtain();/*from w w w .j av a 2 s. c o m*/ msg.what = 0; msg.obj = "empty"; try { // create an http client with a get request // for our url HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpGet httpGet = new HttpGet(url.toString()); // set the User-Agent List<Header> headers = new ArrayList<Header>(); headers.add(new BasicHeader("User-Agent", USER_AGENT)); httpClient.getParams().setParameter(ClientPNames.DEFAULT_HEADERS, headers); // execute the request HttpResponse resp = httpClient.execute(httpGet, localContext); BufferedReader in = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); String inputLine; response = ""; while ((inputLine = in.readLine()) != null) response += inputLine; in.close(); msg.what = 1; msg.obj = response; } catch (IOException e) { msg.what = 0; msg.obj = "io exception : " + url.toString(); } finally { handler.sendMessage(msg); } }
From source file:org.openintents.updatechecker.UpdateChecker.java
public VeecheckResult performRequest(VeecheckVersion version, String uri) throws ClientProtocolException, IOException, IllegalStateException, SAXException { HttpClient client = new DefaultHttpClient(); // TODO ideally it should be possible to adjust these constants HttpParams params = client.getParams(); HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, SO_TIMEOUT); HttpGet request = new HttpGet(version.substitute(uri)); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); try {//w ww . j a v a 2 s. com StatusLine line = response.getStatusLine(); // TODO this is lazy, we should consider other codes here if (line.getStatusCode() != 200) throw new IOException("Request failed: " + line.getReasonPhrase()); Header header = response.getFirstHeader(HTTP.CONTENT_TYPE); Encoding encoding = identityEncoding(header); VeecheckResult handler = new VeecheckResult(version); Xml.parse(entity.getContent(), encoding, handler); return handler; } finally { entity.consumeContent(); } }
From source file:bookkeepr.BookKeepr.java
/** * This loads the configuration file and sets the intial settings. *///from w ww . ja v a 2s .c o m public BookKeepr(File configFile) { try { this.configFile = configFile; if (!configFile.exists()) { config = new BookkeeprConfig(); config.setOriginId(0); saveConfig(); } config = (BookkeeprConfig) XMLReader.read(new FileInputStream(configFile)); if (config.getOriginId() < 0 || config.getOriginId() > 255) { config.setOriginId(0); } if (config.getOriginId() == 0) { Logger.getLogger(BookKeepr.class.getName()).log(Level.INFO, "Client mode active, creation or modification disabled"); } statusMon = new BookKeeprStatusMonitor(); Logger logger = Logger.getLogger("bookkeepr"); logger.setLevel(Level.ALL); logger.setUseParentHandlers(false); logger.addHandler(statusMon); } catch (SAXException ex) { Logger.getLogger(BookKeepr.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(BookKeepr.class.getName()).log(Level.SEVERE, null, ex); } for (int i = 0; i < 20; i++) { HttpClient httpclient = new DefaultHttpClient(); HttpClientParams.setRedirecting(httpclient.getParams(), false); HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 10000); if (config.getProxyUrl() != null) { final HttpHost proxy = new HttpHost(config.getProxyUrl(), config.getProxyPort(), "http"); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } httpClients.add(httpclient); } }