List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.fada.sellsteward.myweibo.sina.net.Utility.java
public static HttpClient getNewHttpClient(Context context) { try {/*from ww w . java 2s. c o m*/ KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new MySSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); // Set the default socket timeout (SO_TIMEOUT) // in // milliseconds which is the timeout for waiting for data. HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT); HttpClient client = new DefaultHttpClient(ccm, params); WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { // ??APN Uri uri = Uri.parse("content://telephony/carriers/preferapn"); Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.moveToFirst()) { // ??? String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { HttpHost proxy = new HttpHost(proxyStr, 80); client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } mCursor.close(); } } return client; } catch (Exception e) { return new DefaultHttpClient(); } }
From source file:com.streamreduce.AbstractInContainerTestCase.java
/** * Logs in the given user and returns the user's authentication token. * * @param username the username to login as * @param password the password for the username * @return the user's authentication token * @throws Exception if something goes wrong *//*w ww .j a v a 2 s . c o m*/ public String login(String username, String password) throws Exception { HttpClient httpClient = new DefaultHttpClient(); // Set the User-Agent to be safe httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, Constants.NODEABLE_HTTP_USER_AGENT); HttpPost post = new HttpPost(getPublicUrlBase() + "/authentication/login"); // HttpState state = httpClient.getState(); String authnToken; try { // Login is done via Basic Authentication at this time // state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME), // new UsernamePasswordCredentials(username, password)); HttpResponse httpReponse = httpClient.execute(post); Header authHeader = httpReponse.getFirstHeader(Constants.NODEABLE_AUTH_TOKEN); if (authHeader != null) { authnToken = httpReponse.getFirstHeader(Constants.NODEABLE_AUTH_TOKEN).getValue(); } else { String response = IOUtils.toString(httpReponse.getEntity().getContent()); try { ErrorMessage em = jsonToObject(response, TypeFactory.defaultInstance().constructType(ErrorMessage.class)); throw new Exception(em.getErrorMessage()); } catch (Exception e) { throw new Exception("Unable to login: " + response); } } } finally { post.releaseConnection(); } return authnToken; }
From source file:com.vmware.vchs.publicapi.samples.HttpUtils.java
/** * This method returns an HttpClient instance wrapped to trust all HTTPS certificates. * /* w w w . j a v a 2 s . c om*/ * @return HttpClient a new instance of HttpClient */ static HttpClient createHttpClient() { HttpClient base = new DefaultHttpClient(); try { SSLContext ctx = SSLContext.getInstance("TLS"); // WARNING: This creates a TrustManager that trusts all certificates and should not be used in production code. TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { } } }; ctx.init(null, trustAllCerts, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:com.jute.fed4j.engine.component.http.HttpDispatcherImpl_Jakarta.java
public void run(HttpComponent component) { this.commponent = component; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, component.connectTimeout); HttpConnectionParams.setSoTimeout(params, component.readTimeout); try {//w ww . j ava 2 s . com this.init(component); HttpClient httpclient = new MyHttpClient( getConnectionManager(params, component.enablePersistentConnection), params); if (component.enableProxy && "http".equals(component.proxyType)) { HttpHost proxy = new HttpHost(component.proxyHost, component.proxyPort, component.proxyType); httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } HttpUriRequest request = new HttpRequest(component.method, component.uri); MyHttpResponseHandler responseHandler = new MyHttpResponseHandler(component.responseCharset); String body = httpclient.execute(request, responseHandler); this.onResponse(component, responseHandler.code, body); } catch (SocketTimeoutException e) { onException(component, -2, " socket timeout error occurs: " + e.getMessage()); } catch (ClientProtocolException e) { onException(component, -3, " error resposed from server: " + e.getMessage()); } catch (IOException e) { onException(component, -4, " error occurs during dispatch: " + e.getMessage()); } catch (Exception e) { onException(component, -5, "error occurs during parsing xml:" + e.getMessage()); } }
From source file:org.openntf.xpt.agents.master.ClientSSLResistanceExtender.java
public static HttpClient wrapClient(HttpClient base) { try {/*from w w w . j a v a 2 s . c om*/ SSLContext ctx = SSLContext.getInstance("sslv3"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; X509HostnameVerifier verifier = new X509HostnameVerifier() { public void verify(String arg0, SSLSocket arg1) throws IOException { } public void verify(String arg0, X509Certificate arg1) throws SSLException { } public void verify(String arg0, String[] arg1, String[] arg2) throws SSLException { } public boolean verify(String hostname, SSLSession session) { return true; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, verifier); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", 443, ssf)); return new DefaultHttpClient(ccm, base.getParams()); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:de.madvertise.android.sdk.Ad.java
/** * Download an image from given URL and return it as byte array. * //from www . j av a 2 s . com * @param imageURLString * url of the banner * @return * image as byte array */ private byte[] downloadImage(String imageURLString) { InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = null; HttpClient client = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(imageURLString); HttpResponse response = null; byte[] returnByteArray = null; if (imageURLString == null) { return returnByteArray; } HttpParams clientParams = client.getParams(); HttpConnectionParams.setConnectionTimeout(clientParams, MadUtil.CONNECTION_TIMEOUT.intValue()); HttpConnectionParams.setSoTimeout(clientParams, MadUtil.CONNECTION_TIMEOUT.intValue()); MadUtil.logMessage(null, Log.DEBUG, "Try to download banner: " + imageURLString); try { response = client.execute(getRequest); MadUtil.logMessage(null, Log.DEBUG, "Response Code=> " + response.getStatusLine().getStatusCode()); HttpEntity entity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode == 200 && entity != null) { inputStream = response.getEntity().getContent(); byteArrayOutputStream = new ByteArrayOutputStream(); int input = inputStream.read(); while (input != -1) { byteArrayOutputStream.write(input); input = inputStream.read(); } returnByteArray = byteArrayOutputStream.toByteArray(); } else { MadUtil.logMessage(null, Log.DEBUG, "Could not download banner because response code is " + responseCode + " (expected 200) or empty body"); } } catch (IOException e) { MadUtil.logMessage(null, Log.DEBUG, "Cannot fetch banner or icon from server"); e.printStackTrace(); } finally { // close all streams if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (byteArrayOutputStream != null) { try { byteArrayOutputStream.close(); } catch (IOException e) { } } } return returnByteArray; }
From source file:custom.application.login.java
public String http_client(String url) throws ApplicationException { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); HttpResponse http_response;/*from ww w . j av a 2 s . c om*/ try { http_response = httpClient.execute(httpget); HeaderIterator iterator = http_response.headerIterator(); while (iterator.hasNext()) { Header next = iterator.nextHeader(); System.out.println(next.getName() + ":" + next.getValue()); } InputStream instream = http_response.getEntity().getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = instream.read(bytes)) != -1) { out.write(bytes, 0, len); } instream.close(); out.close(); return new String(out.toByteArray(), "utf-8"); } catch (ClientProtocolException e) { throw new ApplicationException(e.getMessage(), e); } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } }
From source file:org.andstatus.app.net.HttpConnectionBasic.java
@Override public JSONObject postRequest(HttpPost postMethod) throws ConnectionException { String method = "postRequest"; String result = "?"; JSONObject jObj = null;//from w ww . jav a2 s . c o m int statusCode = 0; try { HttpClient client = HttpApacheUtils.getHttpClient(); postMethod.setHeader("User-Agent", HttpConnection.USER_AGENT); if (getCredentialsPresent()) { postMethod.addHeader("Authorization", "Basic " + getCredentials()); } client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, MyPreferences.getConnectionTimeoutMs()); client.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, MyPreferences.getConnectionTimeoutMs()); HttpResponse httpResponse = client.execute(postMethod); statusCode = httpResponse.getStatusLine().getStatusCode(); result = retrieveInputStream(httpResponse.getEntity()); jObj = new JSONObject(result); if (jObj != null) { String error = jObj.optString("error"); if ("Could not authenticate you.".equals(error)) { throw new ConnectionException(error); } } } catch (UnsupportedEncodingException e) { MyLog.e(this, e); } catch (JSONException e) { throw ConnectionException.loggedJsonException(this, e, result, method); } catch (Exception e) { MyLog.e(this, method, e); throw new ConnectionException(e); } finally { postMethod.abort(); } parseStatusCode(statusCode); return jObj; }
From source file:com.oneguy.recognize.engine.GoogleStreamingEngine.java
byte[] getHttpData(String url) { String TAG = "getHttpData"; HttpGet httpGet = new HttpGet(url); byte[] result = null; try {/*ww w . j a v a 2 s. co m*/ HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT); Log.d(TAG, "HTTP GET:" + httpGet.getURI() + " method:" + httpGet.getMethod()); HttpResponse httpResponse = client.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toByteArray(httpResponse.getEntity()); Log.d(TAG, new String(result)); StreamResponse response = new StreamResponse(null, Status.SUCCESS); response.setResponse(result); response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); Message msg = new Message(); msg.what = EVENT_RESPONSE; msg.obj = response; mHandler.sendMessage(msg); } } catch (ClientProtocolException e) { onError(e); e.printStackTrace(); } catch (IOException e) { onError(e); e.printStackTrace(); } return result; }