使用HttpClient发送Post Http请求
最近需要使用java对Rest接口进行调用,也就是直接使用java直接发送Post, Get, Put, Delete等请求。
印象中可以使用Apache Common下的HttpClient来做,结果HttpClient已经独立成了HttpComponent,编码方式也有所改变。
Google出来的很多文章多数是common-httpclient的方式,在新版本中不怎么适用。经过一番研究自己做了一下封装:
- package cn.com.dayang.auth;
- import java.io.IOException;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.ParseException;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.client.methods.HttpUriRequest;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.protocol.HTTP;
- import org.apache.http.util.EntityUtils;
- import org.apache.log4j.Logger;
- public class HttpXmlClient {
- private static Logger log = Logger.getLogger(HttpXmlClient.class);
- public static String post(String url, Map<String, String> params) {
- DefaultHttpClient httpclient = new DefaultHttpClient();
- String body = null;
- log.info("create httppost:" + url);
- HttpPost post = postForm(url, params);
- body = invoke(httpclient, post);
- httpclient.getConnectionManager().shutdown();
- return body;
- }
- public static String get(String url) {
- DefaultHttpClient httpclient = new DefaultHttpClient();
- String body = null;
- log.info("create httppost:" + url);
- HttpGet get = new HttpGet(url);
- body = invoke(httpclient, get);
- httpclient.getConnectionManager().shutdown();
- return body;
- }
- private static String invoke(DefaultHttpClient httpclient,
- HttpUriRequest httpost) {
- HttpResponse response = sendRequest(httpclient, httpost);
- String body = paseResponse(response);
- return body;
- }
- private static String paseResponse(HttpResponse response) {
- log.info("get response from http server..");
- HttpEntity entity = response.getEntity();
- log.info("response status: " + response.getStatusLine());
- String charset = EntityUtils.getContentCharSet(entity);
- log.info(charset);
- String body = null;
- try {
- body = EntityUtils.toString(entity);
- log.info(body);
- } catch (ParseException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return body;
- }
- private static HttpResponse sendRequest(DefaultHttpClient httpclient,
- HttpUriRequest httpost) {
- log.info("execute post...");
- HttpResponse response = null;
- try {
- response = httpclient.execute(httpost);
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- private static HttpPost postForm(String url, Map<String, String> params){
- HttpPost httpost = new HttpPost(url);
- List<NameValuePair> nvps = new ArrayList <NameValuePair>();
- Set<String> keySet = params.keySet();
- for(String key : keySet) {
- nvps.add(new BasicNameValuePair(key, params.get(key)));
- }
- try {
- log.info("set utf-8 form entity to httppost");
- httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- return httpost;
- }
- }
package cn.com.dayang.auth; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; public class HttpXmlClient { private static Logger log = Logger.getLogger(HttpXmlClient.class); public static String post(String url, Map<String, String> params) { DefaultHttpClient httpclient = new DefaultHttpClient(); String body = null; log.info("create httppost:" + url); HttpPost post = postForm(url, params); body = invoke(httpclient, post); httpclient.getConnectionManager().shutdown(); return body; } public static String get(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(); String body = null; log.info("create httppost:" + url); HttpGet get = new HttpGet(url); body = invoke(httpclient, get); httpclient.getConnectionManager().shutdown(); return body; } private static String invoke(DefaultHttpClient httpclient, HttpUriRequest httpost) { HttpResponse response = sendRequest(httpclient, httpost); String body = paseResponse(response); return body; } private static String paseResponse(HttpResponse response) { log.info("get response from http server.."); HttpEntity entity = response.getEntity(); log.info("response status: " + response.getStatusLine()); String charset = EntityUtils.getContentCharSet(entity); log.info(charset); String body = null; try { body = EntityUtils.toString(entity); log.info(body); } catch (ParseException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return body; } private static HttpResponse sendRequest(DefaultHttpClient httpclient, HttpUriRequest httpost) { log.info("execute post..."); HttpResponse response = null; try { response = httpclient.execute(httpost); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; } private static HttpPost postForm(String url, Map<String, String> params){ HttpPost httpost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList <NameValuePair>(); Set<String> keySet = params.keySet(); for(String key : keySet) { nvps.add(new BasicNameValuePair(key, params.get(key))); } try { log.info("set utf-8 form entity to httppost"); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return httpost; } }
如何调用:
- Map<String, String> params = new HashMap<String, String>();
- params.put("name", name);
- params.put("password", password);
- String xml = HttpXmlClient.post(loginUrl, params);
- log.info(xml);
相关推荐
try(CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(url); StringEntity stringEntity = new StringEntity(params, Charset.forName("UTF-8")); ...
本篇文章将深入探讨如何使用HTTPClient发送POST请求,以及相关的项目结构和实现细节。 首先,"post-demo"项目定义了我们需要调用的接口。通常,这会是一个Web服务,可能是一个RESTful API,提供特定的功能或数据。...
接下来,我们将探讨如何使用HTTPClient发送POST请求并附带JSON数据。首先,你需要创建一个`CloseableHttpClient`实例,然后使用`HttpPost`对象来指定请求URL。在POST请求中,我们将使用`EntityBuilder`来构建包含...
在Java中使用HttpClient发送GET请求相对简单。首先,需要创建一个`HttpClient`实例,然后使用`HttpGet`类构建一个GET请求,并设置请求URL。接下来,调用`execute()`方法来执行请求,最后解析返回的响应。 ##### ...
接下来,我们将详细讲解如何使用HttpClient发送POST请求并携带JSON数据。首先,创建一个HttpClient对象,然后创建HttpPost实例,设置请求URL。例如: ```java CloseableHttpClient httpClient = HttpClients.create...
对于POST请求,你需要创建一个HttpPost对象,并设置请求体: ```java HttpPost httpPost = new HttpPost("http://example.com"); List<NameValuePair> params = new ArrayList(); params.add(new ...
### 使用HttpClient发送POST请求,并获取响应内容 #### 一、简介 在现代软件开发中,尤其是在Web应用领域,客户端与服务器之间的通信是非常重要的环节。Java作为一种广泛应用的编程语言,提供了多种方式来实现这一...
在使用HttpClient发送POST请求时,我们需要关心两个方面的问题:一是如何忽略证书验证过程,二是如何发送POST请求。对于前者,我们可以使用X509TrustManager来忽略证书验证过程。对于后者,我们可以使用HttpPost对象...
通过上述内容,你应该对使用HttpClient发送HTTP请求有了基本的理解。实践中,可以根据具体需求进行更复杂的定制和配置。在实际项目中,HttpClient是一个强大而灵活的工具,能够帮助你轻松地处理网络通信任务。
以下是一个使用HttpClient发送POST请求的Java代码示例: ```java import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import...
Java 使用 HttpClient 发送 POST 请求是网络编程中常见的任务,尤其在与 Web 服务进行交互时。Apache HttpClient 是一个强大的库,允许 Java 开发者轻松地执行 HTTP 请求。在这个示例中,我们将深入探讨如何使用 ...
对于POST请求,我们需要创建一个HttpPost对象,并设置请求URL。如果需要发送JSON数据,我们可以使用StringEntity: ```java HttpPost httpPost = new HttpPost("http://example.com"); httpPost.setHeader("Accept...
在本文中,我们将深入探讨如何使用HttpClient发送POST请求,以及处理JSON参数和其他关键点。 1. 创建HttpClient实例: HttpClient的初始化通常涉及构建一个HttpClientBuilder对象,然后调用其build()方法来创建...
总的来说,HttpClient发送POST请求的基本步骤包括创建HttpClient和HttpPost对象,设置请求实体,执行请求,处理响应。在实际开发中,根据具体需求,你可能需要添加更多的错误处理和逻辑判断,以确保程序的健壮性。...
3. **HttpGet** 和 **HttpPost**:这两个类分别代表了HTTP的GET和POST请求,是最常见的HTTP操作。它们继承自HttpRequestBase,并提供了设置URL、添加请求头和请求体的方法。 4. **HttpResponse**:表示HTTP响应,...
httpclient的用法,发送get请求和post请求,设置header
同时,通过阅读如"HttpClient发送get请求和post请求"这样的博客,你可以获取更多关于HttpClient实战中的技巧和最佳实践。在提供的压缩包文件中,`test-demo`和`httpclient-demo`可能包含了这些示例的源码,供你...