List of usage examples for org.apache.http.client HttpClient getParams
@Deprecated HttpParams getParams();
From source file:com.ljt.openapi.demo.util.HttpUtil.java
/** * Http POST /*from w w w. j a v a 2 s. c o m*/ * * @param host * @param path * @param connectTimeout * @param headers * @param querys * @param body * @param signHeaderPrefixList * @param appKey * @param appSecret * @return * @throws Exception */ public static Response httpPost(String host, String path, int connectTimeout, Map<String, String> headers, Map<String, String> querys, String body, List<String> signHeaderPrefixList, String appKey, String appSecret, boolean isSend) throws Exception { headers = initialBasicHeader(HttpMethod.POST, path, headers, querys, null, signHeaderPrefixList, appKey, appSecret); HttpClient httpClient = wrapClient(host); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(connectTimeout)); HttpPost post = new HttpPost(initUrl(host, path, querys)); for (Map.Entry<String, String> e : headers.entrySet()) { post.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue())); } if (StringUtils.isNotBlank(body)) { post.setEntity(new StringEntity(body, Constants.ENCODING)); } logPost(post); if (isSend) { return convert(httpClient.execute(post)); } else { return null; } }
From source file:com.vanda.beivandalibnetwork.utils.HttpUtils.java
/** * Execute a specific request//www . j a va2s . com * * @param request * Request from user * @param context * Context to use for the request * @param ctimeout * Cache timeout * @param sotimeout * So timeout * @return * @throws IOException * @throws ClientProtocolException */ public static String execute(HttpUriRequest request, HttpContext context, int ctimeout, int sotimeout) throws IOException { String result = null; HttpClient client = new DefaultHttpClient(); if (context == null) context = CURRENT_CONTEXT; try { HttpConnectionParams.setConnectionTimeout(client.getParams(), ctimeout); HttpConnectionParams.setSoTimeout(client.getParams(), sotimeout); HttpProtocolParams.setUseExpectContinue(client.getParams(), false); HttpResponse resp = client.execute(request, context); result = EntityUtils.toString(resp.getEntity(), getContentEncoding(resp)); } catch (ClientProtocolException e) { Logger.warn(TAG, "[execute]Error when calling url >> " + request.getURI(), e); } // } catch (IOException e) { // if(e instanceof ConnectTimeoutException){ // if(l != null) // l.connectTimeOutInter(); // } // if(e instanceof SocketTimeoutException){ // if(l != null) // l.socketTimeOutInter(); // // } // Logger.warn(TAG, "[execute]IOException when calling url >> " + // request.getURI(), e); // } return result; }
From source file:com.mobile.natal.natalchart.NetworkUtilities.java
/** * Sends a {@link MultipartEntity} post with text and image files. * * @param url the url to which to POST to. * @param user the user or <code>null</code>. * @param pwd the password or <code>null</code>. * @param stringsMap the {@link HashMap} containing the key and string pairs to send. * @param filesMap the {@link HashMap} containing the key and image file paths * (jpg, png supported) pairs to send. * @throws Exception if something goes wrong. *//*w w w . ja v a2s. co m*/ public static void sentMultiPartPost(String url, String user, String pwd, HashMap<String, String> stringsMap, HashMap<String, File> filesMap) throws Exception { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); if (user != null && pwd != null && user.trim().length() > 0 && pwd.trim().length() > 0) { String ret = getB64Auth(user, pwd); httppost.setHeader("Authorization", ret); } MultipartEntity mpEntity = new MultipartEntity(); Set<Entry<String, String>> stringsEntrySet = stringsMap.entrySet(); for (Entry<String, String> stringEntry : stringsEntrySet) { ContentBody cbProperties = new StringBody(stringEntry.getValue()); mpEntity.addPart(stringEntry.getKey(), cbProperties); } Set<Entry<String, File>> filesEntrySet = filesMap.entrySet(); for (Entry<String, File> filesEntry : filesEntrySet) { String propName = filesEntry.getKey(); File file = filesEntry.getValue(); if (file.exists()) { String ext = file.getName().toLowerCase().endsWith("jpg") ? "jpeg" : "png"; ContentBody cbFile = new FileBody(file, "image/" + ext); mpEntity.addPart(propName, cbFile); } } httppost.setEntity(mpEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity(); if (resEntity != null) { resEntity.consumeContent(); } httpclient.getConnectionManager().shutdown(); }
From source file:com.upyun.sdk.utils.HttpClientUtils.java
private static HttpResponse put(String url, HttpClient httpclient, Map<String, String> headers, InputStream instream, Integer length) { HttpPut httpPut = new HttpPut(url); HttpResponse response = null;// w w w . j ava2 s.co m if (headers != null) { for (String key : headers.keySet()) { httpPut.addHeader(key, headers.get(key)); } } InputStreamEntity ise = new InputStreamEntity(instream, length); httpPut.setEntity(ise); httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);// httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, SO_TIMEOUT); // ? try { response = httpclient.execute(httpPut); } catch (Exception e) { LogUtil.exception(logger, e); } return response; }
From source file:net.lamp.support.HttpManager.java
/** * ? URL ?? * //from w w w. jav a2 s . c om * @param context ?? * @param url ?? * @param method "GET" or "POST" * @param params ?? * @param file ??????SdCard ? * * @return ? * @throws WeiboException ? */ public static ByteArrayOutputStream openUrl4Binary(Context context, String url, String method, WeiboParameters params, String file) throws WeiboException { ByteArrayOutputStream result = null; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); Utility.UploadImageUtils.revitionPostImageSize(context, file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { String resultStr = readHttpResponse(response); // throw new WeiboHttpException(resultStr, statusCode); } result = readBytesFromHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:net.lamp.support.HttpManager.java
/** * ? URL ?? * // w w w .jav a2s .c om * @param url ?? * @param method "GET" or "POST" * @param params ?? * @param file ?????? SdCard ? * * @return ? * @throws WeiboException ? */ public static String openUrl(String url, String method, WeiboParameters params, String file) throws WeiboException { String result = ""; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); // ? // Utility.UploadImageUtils.revitionPostImageSize(file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = readHttpResponse(response); // throw new WeiboHttpException(result, statusCode); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:net.lamp.support.HttpManager.java
/** * ???? formdata name="pic" name="file" ???????? * * @param url ?? * @param method "GET" or "POST" * @param params ?? * @param file ??????SdCard ? * /* www .j a va 2 s . c o m*/ * @return ? * @throws WeiboException ? */ public static String uploadFile(String url, String method, WeiboParameters params, String file) throws WeiboException { String result = ""; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); // ? // Utility.UploadImageUtils.revitionPostImageSize(file); fileToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { result = readHttpResponse(response); // throw new WeiboHttpException(result, statusCode); } result = readHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }
From source file:org.apache.camel.component.box.internal.BoxClientHelper.java
@SuppressWarnings("deprecation") public static CachedBoxClient createBoxClient(final BoxConfiguration configuration) { final String clientId = configuration.getClientId(); final String clientSecret = configuration.getClientSecret(); final IAuthSecureStorage authSecureStorage = configuration.getAuthSecureStorage(); final String userName = configuration.getUserName(); final String userPassword = configuration.getUserPassword(); if ((authSecureStorage == null && ObjectHelper.isEmpty(userPassword)) || ObjectHelper.isEmpty(userName) || ObjectHelper.isEmpty(clientId) || ObjectHelper.isEmpty(clientSecret)) { throw new IllegalArgumentException("Missing one or more required properties " + "clientId, clientSecret, userName and either authSecureStorage or userPassword"); }//from ww w .j av a 2 s. c o m LOG.debug("Creating BoxClient for login:{}, client_id:{} ...", userName, clientId); // if set, use configured connection manager builder final BoxConnectionManagerBuilder connectionManagerBuilder = configuration.getConnectionManagerBuilder(); final BoxConnectionManagerBuilder connectionManager = connectionManagerBuilder != null ? connectionManagerBuilder : new BoxConnectionManagerBuilder(); // create REST client for BoxClient final ClientConnectionManager[] clientConnectionManager = new ClientConnectionManager[1]; final IBoxRESTClient restClient = new BoxRESTClient(connectionManager.build()) { @Override public HttpClient getRawHttpClient() { final HttpClient httpClient = super.getRawHttpClient(); clientConnectionManager[0] = httpClient.getConnectionManager(); // set custom HTTP params final Map<String, Object> configParams = configuration.getHttpParams(); if (configParams != null && !configParams.isEmpty()) { LOG.debug("Setting {} HTTP Params", configParams.size()); final HttpParams httpParams = httpClient.getParams(); for (Map.Entry<String, Object> param : configParams.entrySet()) { httpParams.setParameter(param.getKey(), param.getValue()); } } return httpClient; } }; final BoxClient boxClient = new BoxClient(clientId, clientSecret, null, null, restClient, configuration.getBoxConfig()); // enable OAuth auto-refresh boxClient.setAutoRefreshOAuth(true); // wrap the configured storage in a caching storage final CachingSecureStorage storage = new CachingSecureStorage(authSecureStorage); // set up a listener to notify secure storage and user provided listener, store it in configuration! final OAuthHelperListener listener = new OAuthHelperListener(storage, configuration.getRefreshListener()); boxClient.addOAuthRefreshListener(listener); final CachedBoxClient cachedBoxClient = new CachedBoxClient(boxClient, userName, clientId, storage, listener, clientConnectionManager); LOG.debug("BoxClient created {}", cachedBoxClient); return cachedBoxClient; }
From source file:com.lurencun.cfuture09.androidkit.http.Http.java
/** * //w ww .j ava 2 s .c om * * @param url * ?URL * @param entity * * @return ? * @throws ClientProtocolException * @throws IOException */ private static String doUpload(String url, SimpleMultipartEntity entity) throws ClientProtocolException, IOException { HttpClient httpclient = null; try { httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpPost httppost = new HttpPost(url); httppost.setEntity(entity); HttpResponse response; response = httpclient.execute(httppost); return EntityUtils.toString(response.getEntity()); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } }
From source file:cn.edu.mju.Thriphoto.net.HttpManager.java
/** * ? URL ?// ww w .j a va2 s .c o m * * @param context ? * @param url ? * @param method "GET" or "POST" * @param params ? * @param file ????? SdCard ? * * @return ? * @throws com.sina.weibo.sdk.exception.WeiboException ? */ public static ByteArrayOutputStream openUrl4Binary(Context context, String url, String method, WeiboParameters params, String file) throws WeiboException { ByteArrayOutputStream result = null; try { HttpClient client = getNewHttpClient(); HttpUriRequest request = null; ByteArrayOutputStream bos = null; client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN()); if (method.equals(HTTPMETHOD_GET)) { url = url + "?" + Utility.encodeUrl(params); HttpGet get = new HttpGet(url); request = get; } else if (method.equals(HTTPMETHOD_POST)) { HttpPost post = new HttpPost(url); request = post; byte[] data = null; String _contentType = params.getValue("content-type"); bos = new ByteArrayOutputStream(); if (!TextUtils.isEmpty(file)) { paramToUpload(bos, params); post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY); Utility.UploadImageUtils.revitionPostImageSize(context, file); imageContentToUpload(bos, file); } else { if (_contentType != null) { params.remove("content-type"); post.setHeader("Content-Type", _contentType); } else { post.setHeader("Content-Type", "application/x-www-form-urlencoded"); } String postParam = Utility.encodeParameters(params); data = postParam.getBytes("UTF-8"); bos.write(data); } data = bos.toByteArray(); bos.close(); ByteArrayEntity formEntity = new ByteArrayEntity(data); post.setEntity(formEntity); } else if (method.equals("DELETE")) { request = new HttpDelete(url); } HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode != 200) { String resultStr = readHttpResponse(response); throw new WeiboHttpException(resultStr, statusCode); } result = readBytesFromHttpResponse(response); return result; } catch (IOException e) { throw new WeiboException(e); } }