HttpClient 4.X代码样例备忘.其中httpClient 4.0与httpClient 4.3+代码结构少有不同.
1. httpClient 4.0
public class HttpClientUtil { private final static Log log = LogFactory.getLog(HttpClientUtil.class); private static HttpClient httpClient = new DefaultHttpClient();; public static final String CHARSET = "UTF-8"; static { httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 15000); } public static String httpGet(String url, Map<String, String> params){ return httpGet(url, params,"utf-8"); } public static String httpPost(String url, Map<String, String> params){ return httpPost(url, params,"utf-8"); } /** * @param url http://taobao.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpGet(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try { if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpget.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } catch (Exception e) { log.error("http调用异常!url:" + url, e); } finally { httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS); } return null; } /** * @param url http://360buy.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpPost(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try{ HttpPost httpPost = new HttpPost(url); if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } httpPost.setEntity(new UrlEncodedFormEntity(pairs,charset)); } HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpPost.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } catch (Exception e) { log.error("http调用异常!url:" + url, e); } finally { httpClient.getConnectionManager().closeIdleConnections(30, TimeUnit.SECONDS); } return null; } /** * 发送body为form格式 * @param url * @return * @throws Exception */ public static String httpPost(String url,Map<String,String> params,HttpEntity requestEntity) throws Exception{ if(params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } String queryString = EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET)); if(url.indexOf("?") > 0) { url += "&" + queryString; } else { url += "?" + queryString; } } HttpPost httpPost = new HttpPost(url); if(requestEntity != null) { httpPost.setEntity(requestEntity); } CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); return result; } finally { response.close(); } }
2. httpClient 4.3+
public class HttpClientUtil { private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; static { RequestConfig config = RequestConfig.custom() .setConnectTimeout(60000) .setSocketTimeout(15000) .build(); httpClient = HttpClientBuilder.create() .setDefaultRequestConfig(config) .build(); } public static String httpGet(String url, Map<String, String> params){ return httpGet(url, params,"utf-8"); } /** * @param url http://taobao.com/test.action * @param params 参数,编码之前的参数 * @return */ public static String httpGet(String url, Map<String, String> params,String charset) { if(StringUtils.isBlank(url)){ return null; } try { if(params != null && !params.isEmpty()){ List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for(Map.Entry<String,String> entry : params.entrySet()){ String value = entry.getValue(); if(value != null){ pairs.add(new BasicNameValuePair(entry.getKey(),value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpget = new HttpGet(url); CloseableHttpResponse response = httpClient.execute(httpget); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { httpget.abort(); throw new RuntimeException("HttpClient,error status code :" + statusCode); } HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); response.close(); return result; } catch (Exception e) { e.printStackTrace(); } return null; } }
3. httpClient 4.3+中cookie操作
public class HttpUtils { private static final CloseableHttpClient httpClient; public static final String CHARSET = "UTF-8"; static { RequestConfig config = RequestConfig.custom() .setConnectTimeout(6000) .setSocketTimeout(6000) .build(); Registry<CookieSpecProvider> registry = RegistryBuilder.<CookieSpecProvider>create() .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory()) .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory()) .build(); httpClient = HttpClients.custom() .setDefaultRequestConfig(config) .setDefaultCookieSpecRegistry(registry) .setDefaultCookieStore(new BasicCookieStore()) //内存中 .build(); } public static void main(String[] args) throws Exception{ login();//server 端写cookie getOrder();//客户端发送cookie } public static void getOrder() throws Exception{ String url = "http://test.domain/user/order.jhtml"; HttpGet httpGet = new HttpGet(url); HttpClientContext clientContext = HttpClientContext.create(); //默认情况下,httpClient会发送所有的,已接受到的cookie,无需额外的操作 //如果client需要发送额外的cookie值,可以通过如下方式替换 /** CookieStore cookieStore = new BasicCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(Cookie cookie : cookies) { cookieStore.addCookie(cookie); } clientContext.setCookieStore(cookieStore); **/ CloseableHttpResponse response = httpClient.execute(httpGet,clientContext); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); System.out.println(result); } finally { response.close(); } } public static void login() throws Exception{ String url = "http://test.domain/user/login.jhtml"; Map<String,String> params = new HashMap<String,String>(); params.put("phone","18600000000"); params.put("password","123123"); if(params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, CHARSET)); } HttpPost httpPost = new HttpPost(url); HttpClientContext clientContext = HttpClientContext.create(); CloseableHttpResponse response = httpClient.execute(httpPost,clientContext); try { HttpEntity entity = response.getEntity(); String result = null; if (entity != null) { result = EntityUtils.toString(entity, "utf-8"); } EntityUtils.consume(entity); System.out.println(result);//响应的结果 //获取响应中包含或者"新增"的cookie信息 //这些cookie会被保存在HttpClient全局的cookieStore中,以便此后其他请求使用 CookieStore cookieStore = clientContext.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for(Cookie cookie : cookies) { System.out.println(cookie.getName() + "," + cookie.getValue()); } } finally { response.close(); } } }
4. httpClient与multipart-form提交
String url = "http://test.domain/update_user.jhtml"; HttpPost post = new HttpPost(url); MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); FileBody fileBody = new FileBody(new File("D:\\test.jpg")); entityBuilder.addPart("icon",fileBody);//发送图片 ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8")); StringBody stringBody = new StringBody("张三",contentType); entityBuilder.addPart("name",stringBody); post.setEntity(entityBuilder.build()); CloseableHttpResponse response = httpClient.execute(post); HttpEntity entity = response.getEntity(); String result = null; System.out.println(response.getStatusLine()); if (entity != null) { long length = entity.getContentLength(); System.out.println(length); if (length != -1) { result = EntityUtils.toString(entity, "utf-8"); } } else { System.out.println("11:null"); } EntityUtils.consume(entity); response.close();
5. pom.xml
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.3</version> </dependency>
相关推荐
ATL自带 HTTP Client访问 HTTP Server的Server侧代码。
这个样例项目旨在帮助初学者理解如何在Java中使用HttpClient来与Web服务器进行交互。 在JavaHttpProject这个项目中,你可以找到以下关键知识点: 1. **HttpClient的创建**:首先,你需要创建一个HttpClient实例。...
这篇博客"HTTPS客户端、服务端代码样例"提供了一些关于如何实现HTTPS通信的示例代码,对于理解和应用HTTPS技术非常有帮助。 首先,我们需要了解HTTPS的基础架构。HTTPS在客户端(浏览器)和服务器端之间建立一个...
在提供的代码样例中,开发者可以学习如何使用Java的HttpClient、Json库等工具,构建请求,解析响应,实现与FusionCompute R3的交互。此外,样例还可能涵盖错误处理、认证授权、异步调用等实际开发中的重要环节。 ...
在这种情况下,"【开放平台】_新浪微博JAVA代码样例及详细说明" 提供了使用Java编程语言与新浪微博开放平台进行交互的示例代码和指南。新浪微博是中国极具影响力的社交媒体平台,它提供了丰富的API供开发者构建各种...
《eSDK UC V100R005C10 代码样例 01(UC2.2,REST)》 本代码样例主要针对eSDK UC V100R005C10版本,它是一个企业通信服务平台(Unified Communication, 简称UC)的开发工具包,用于实现UC2.2服务端REST接口的功能。...
在本文中,我们将深入探讨如何使用HttpClient发送请求以及接收响应的完整代码实例。 首先,我们需要引入Apache HttpClient库。如果你使用的是Maven项目,可以在pom.xml文件中添加以下依赖: ```xml <groupId>org...
在提供的压缩包文件“Android拍照上传代码样例(转)”中,你可能找到一个完整的示例项目,包括了上述步骤的具体实现。通过阅读和学习这个样例代码,你可以更好地理解和掌握Android拍照和上传功能的实现细节。记住,...
在本文中,我们将深入探讨这两种方法的实现,并提供相关的样例代码。 首先,让我们理解HTTP GET和POST的区别。GET主要用于从服务器获取资源,它将请求参数附加到URL中,是幂等的,即多次执行同一GET请求,结果相同...
4. **响应解析类**:处理并解析API返回的JSON数据。 5. **异常处理类**:捕获和处理可能出现的网络或API错误。 具体来说,这些Java代码可能实现的功能包括: - **文档创建**:根据指定模板或空白页面创建新文档。 ...
下面是一个简化的C#网络爬虫示例代码片段: ```csharp using System; using System.Net.Http; using HtmlAgilityPack; public class SimpleWebCrawler { private readonly HttpClient _httpClient; public ...
文件"01_demo.pbl"可能是包含示例代码的PowerBuilder库文件,它展示了如何在PB11.2中实际编写和使用POST接口。通过查看和运行这个示例,你可以更直观地学习如何在项目中实现POST接口。 总之,PB11.2中的POST接口...
这里我们以Apache HttpClient为例,展示一个POST请求的源码样例: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache....
4. **错误处理**:编写健壮的代码,处理可能出现的网络错误、API错误以及授权问题。 5. **异步编程**:由于网络请求通常是阻塞的,C#的async/await关键字可以帮助我们编写非阻塞的异步代码,提高程序性能。 在描述...
《cocos游戏样例二_基本塔防游戏》是一份精心整理的游戏开发示例,它包含五个基于Cocos2d-x 3.6版本的项目,适用于Visual Studio 2013开发环境。这些示例代码在网上搜集而来,并且经过验证,确保在本地环境下能够...
上述代码中,我们首先创建了一个`HttpClient`对象,然后使用`PostMethod`来定义请求的目标URL。接着,我们设置了请求头,特别是`Content-Type`,表示我们将发送JSON格式的数据。然后,我们构建了请求正文,并将其...
GeoTracker样例项目是一个基于Java开发的地理追踪应用示例,旨在展示如何使用Java技术来实现位置跟踪和数据管理功能。这个项目可能包含了用于实时地理位置数据处理、存储和展示的核心组件,是学习和理解相关技术的一...
"StoreClient"可能是客户端应用程序代码,"packages"文件夹可能包含了项目依赖的NuGet包。这些文件是构建和运行POST请求示例应用的组成部分。 总之,模仿POST请求是开发过程中的常见操作,涉及到网络通信、数据序列...