List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams
public synchronized final HttpParams getParams()
From source file:com.mhise.util.MHISEUtil.java
public static String CallWebService(String url, String soapAction, String envelope, DefaultHttpClient httpClient) { // request parameters HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 60000); HttpConnectionParams.setSoTimeout(params, 60000); // set parameter HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true); // POST the envelope HttpPost httppost = new HttpPost(url); // add headers httppost.setHeader("action", soapAction); httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8;"); String responseString = ""; try {/* ww w . ja v a 2 s . co m*/ // the entity holds the request HttpEntity entity = new StringEntity(envelope); httppost.setEntity(entity); // Response handler ResponseHandler<String> rh = new ResponseHandler<String>() { // invoked when client receives response public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { //Log.e("CallWebService",getResponseBody(response)); // get response entity HttpEntity entity = response.getEntity(); // read the response as byte array StringBuffer out = new StringBuffer(); byte[] b = EntityUtils.toByteArray(entity); String str = new String(b, 0, b.length); Log.e("string length", "" + str); //int index = b.length-1; //Log.e("b lase string",""+(char)(b[index-2])+(char)(b[index-1])+(char)(b[index])); // write the response byte array to a string buffer out.append(new String(b, 0, b.length)); return out.toString(); //return getResponseBody(response); } }; try { responseString = httpClient.execute(httppost, rh); } catch (Exception e) { Logger.debug("MHISEUtil-->CallWebService -->", "finally clause"); } } catch (Exception e) { Logger.debug("MHISEUtil-->CallWebService -->", "finally clause"); } // close the connection httpClient.getConnectionManager().closeExpiredConnections(); httpClient.getConnectionManager().shutdown(); Log.e("Response", "" + responseString); return responseString; }
From source file:com.capstonecontrol.AccountsActivity.java
/** * Retrieves the authorization cookie associated with the given token. This * method should only be used when running against a production appengine * backend (as opposed to a dev mode server). *//*from w w w .j a v a2 s. c o m*/ private String getAuthCookie(String authToken) { DefaultHttpClient httpClient = new DefaultHttpClient(); try { // Get SACSID cookie httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); String uri = Setup.PROD_URL + "/_ah/login?continue=http://localhost/&auth=" + authToken; HttpGet method = new HttpGet(uri); HttpResponse res = httpClient.execute(method); StatusLine statusLine = res.getStatusLine(); int statusCode = statusLine.getStatusCode(); Header[] headers = res.getHeaders("Set-Cookie"); if (statusCode != 302 || headers.length == 0) { return null; } for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if (AUTH_COOKIE_NAME.equals(cookie.getName())) { return AUTH_COOKIE_NAME + "=" + cookie.getValue(); } } } catch (IOException e) { Log.w(TAG, "Got IOException " + e); Log.w(TAG, Log.getStackTraceString(e)); } finally { httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } return null; }
From source file:com.eTilbudsavis.etasdk.network.impl.DefaultHttpNetwork.java
public HttpResponse performNetworking(Request<?> request) throws ClientProtocolException, IOException { // Start the interwebs work stuff DefaultHttpClient httpClient = new DefaultHttpClient(); request.addEvent("set-apache-routeplanner"); setHostNameVerifierAndRoutePlanner(httpClient); // Set timeouts request.addEvent(String.format("set-connection-timeout-%s", request.getTimeOut() * 2)); HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), request.getTimeOut()); HttpConnectionParams.setSoTimeout(httpClient.getParams(), request.getTimeOut()); // Get the right request type, and set body if necessary HttpRequestBase httpRequest = createRequest(request); setHeaders(request, httpRequest);// www. j a v a 2 s .c o m request.addEvent("performing-http-request"); return httpClient.execute(httpRequest); }
From source file:net.wm161.microblog.lib.backends.statusnet.HTTPAPIRequest.java
protected String getData(URI location) throws APIException { Log.d("HTTPAPIRequest", "Downloading " + location); DefaultHttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(location); client.addRequestInterceptor(preemptiveAuth, 0); client.getParams().setBooleanParameter("http.protocol.expect-continue", false); if (!m_params.isEmpty()) { MultipartEntity params = new MultipartEntity(); for (Entry<String, Object> item : m_params.entrySet()) { Object value = item.getValue(); ContentBody data;/*ww w. j a v a 2s . c o m*/ if (value instanceof Attachment) { Attachment attachment = (Attachment) value; try { data = new InputStreamBody(attachment.getStream(), attachment.contentType(), attachment.name()); Log.d("HTTPAPIRequest", "Found a " + attachment.contentType() + " attachment named " + attachment.name()); } catch (FileNotFoundException e) { getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND); throw new APIException(); } catch (IOException e) { getRequest().setError(ErrorType.ERROR_ATTACHMENT_NOT_FOUND); throw new APIException(); } } else { try { data = new StringBody(value.toString()); } catch (UnsupportedEncodingException e) { getRequest().setError(ErrorType.ERROR_INTERNAL); throw new APIException(); } } params.addPart(item.getKey(), data); } post.setEntity(params); } UsernamePasswordCredentials creds = new UsernamePasswordCredentials(m_api.getAccount().getUser(), m_api.getAccount().getPassword()); client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); HttpResponse req; try { req = client.execute(post); } catch (ClientProtocolException e3) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } catch (IOException e3) { getRequest().setError(ErrorType.ERROR_CONNECTION_FAILED); throw new APIException(); } InputStream result; try { result = req.getEntity().getContent(); } catch (IllegalStateException e1) { getRequest().setError(ErrorType.ERROR_INTERNAL); throw new APIException(); } catch (IOException e1) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } InputStreamReader in = null; int status; in = new InputStreamReader(result); status = req.getStatusLine().getStatusCode(); Log.d("HTTPAPIRequest", "Got status code of " + status); setStatusCode(status); if (status >= 300 || status < 200) { getRequest().setError(ErrorType.ERROR_SERVER); Log.w("HTTPAPIRequest", "Server code wasn't 2xx, got " + m_status); throw new APIException(); } int totalSize = -1; if (req.containsHeader("Content-length")) totalSize = Integer.parseInt(req.getFirstHeader("Content-length").getValue()); char[] buffer = new char[1024]; //2^17 = 131072. StringBuilder contents = new StringBuilder(131072); try { int size = 0; while ((totalSize > 0 && size < totalSize) || totalSize == -1) { int readSize = in.read(buffer); size += readSize; if (readSize == -1) break; if (totalSize >= 0) getRequest().publishProgress(new APIProgress((size / totalSize) * 5000)); contents.append(buffer, 0, readSize); } } catch (IOException e) { getRequest().setError(ErrorType.ERROR_CONNECTION_BROKEN); throw new APIException(); } return contents.toString(); }
From source file:com.mediaportal.ampdroid.activities.videoplayback.StreamProxy.java
private HttpResponse download(String url) { DefaultHttpClient seed = new DefaultHttpClient(); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SingleClientConnManager mgr = new SingleClientConnManager(seed.getParams(), registry); DefaultHttpClient http = new DefaultHttpClient(mgr, seed.getParams()); HttpGet method = new HttpGet(url); HttpResponse response = null;/*ww w .j a v a2s.co m*/ try { Log.d(LOG_TAG, "starting download"); response = http.execute(method); Log.d(LOG_TAG, "downloaded"); } catch (ClientProtocolException e) { Log.e(LOG_TAG, "Error downloading", e); } catch (IOException e) { Log.e(LOG_TAG, "Error downloading", e); } return response; }
From source file:com.android.sdklib.internal.repository.UrlOpener.java
private static InputStream openWithHttpClient(String url, ITaskMonitor monitor) throws IOException, ClientProtocolException, CanceledByUserException { UserCredentials result = null;/*from w w w. j a v a2 s.co m*/ String realm = null; // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(); // create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet(url); // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. return new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { super.close(); // since Http Client is no longer needed, close it httpClient.getConnectionManager().shutdown(); } }; } } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }