httpClient发送post请求,带header、body的工具类

自己写一个发送http post请求的工具类,因为需要头部和参数,网上没有合适的,拿出来分享下
只需要传三个参数:地址,头部map,bodymap
另外响应已经将body取出并转成字符串返回

maven引入httpClient

<!-- httpClient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>

代码

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;


public String postMap(String url,Map<String,String> headerMap,Map<String, String> contentMap) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        List<NameValuePair> content = new ArrayList<NameValuePair>();
        Iterator iterator = contentMap.entrySet().iterator();           //将content生成entity
        while(iterator.hasNext()){  
            Entry<String,String> elem = (Entry<String, String>) iterator.next();  
            content.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
        }
        CloseableHttpResponse response = null;
        try {
            Iterator headerIterator = headerMap.entrySet().iterator();          //循环增加header
            while(headerIterator.hasNext()){  
                Entry<String,String> elem = (Entry<String, String>) headerIterator.next();  
                post.addHeader(elem.getKey(),elem.getValue());
            }
            if(content.size() > 0){  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(content,"UTF-8");  
                post.setEntity(entity);
            }
            response = httpClient.execute(post);            //发送请求并接收返回数据
            if(response != null && response.getStatusLine().getStatusCode() == 200)
            {
                HttpEntity entity = response.getEntity();       //获取response的body部分
                result = EntityUtils.toString(entity);          //读取reponse的body部分并转化成字符串
            }
            return result;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                httpClient.close();
                if(response != null)
                {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
  • 6
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: HttpClient发送POST请求时,可以通过设置请求体(body)来传递参数或数据。具体步骤如下: 1. 创建HttpClient对象 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpPost对象,并设置请求URL ``` HttpPost httpPost = new HttpPost("http://example.com/api"); ``` 3. 创建请求体(body),并设置请求头 ``` String requestBody = "{\"name\":\"John\", \"age\":30}"; StringEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); httpPost.setEntity(entity); ``` 4. 发送请求,并获取响应 ``` CloseableHttpResponse response = httpClient.execute(httpPost); ``` 5. 处理响应 ``` HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity); System.out.println(responseBody); ``` 以上就是使用HttpClient发送POST请求并设置请求体的基本步骤。需要注意的是,请求体的格式和内容应该根据API文档或接口规范进行设置。 ### 回答2: HttpClient是一个开源的Java HTTP客户端工具包,可以用来发送HTTP请求。在发送POST请求时,我们需要往请求体中添加参数,这就需要用到HttpClient发送POST请求bodyHttpClient发送POST请求有两种方法:使用NameValuePair键值对和使用字符串。两种方法的使用取决于请求的内容。如果是简单的键值对,可以使用NameValuePair键值对;如果请求内容较为复杂,需要包含一些json格式的数据,那么就需要使用字符串的方式。 使用NameValuePair键值对发送POST请求: NameValuePair是一种存储参数的方法,我们可以通过NameValuePair将参数键值对添加到请求体中,代码示例如下: ``` // 创建一个 HttpClient 客户端 CloseableHttpClient httpClient = HttpClients.createDefault(); // 设置请求地址 HttpPost httpPost = new HttpPost("http://localhost:8080/test"); // 设置请求头部信息 httpPost.setHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8"); // 设置请求参数 List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); // 设置请求体 httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); // 执行请求并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); // 获取响应消息实体 HttpEntity responseEntity = response.getEntity(); // 打印响应内容 System.out.println(EntityUtils.toString(responseEntity)); // 关闭响应对象 response.close(); // 关闭客户端对象 httpClient.close(); ``` 使用字符串发送POST请求发送POST请求时,我们可以将请求体中需要传递的json对象转换成字符串形式,然后将该字符串作为请求发送。代码示例如下: ``` // 创建一个 HttpClient 客户端 CloseableHttpClient client = HttpClients.createDefault(); // 设置请求地址 HttpPost post = new HttpPost("http://localhost:8080/test"); // 设置请求头部信息 post.setHeader("Content-Type", "application/json; charset=utf-8"); // 设置请求体 StringEntity entity = new StringEntity("{\"username\":\"admin\",\"password\":\"admin\"}", "UTF-8"); post.setEntity(entity); // 执行请求并获取响应 CloseableHttpResponse response = client.execute(post); // 获取响应消息实体 HttpEntity responseEntity = response.getEntity(); // 打印响应内容 System.out.println(EntityUtils.toString(responseEntity)); // 关闭响应对象 response.close(); // 关闭客户端对象 client.close(); ``` 以上就是使用HttpClient发送POST请求body的方法,通过该方法可以方便地处理POST请求,以此实现数据的传输和接收。需要注意的是,在发送POST请求的同时需注意设置请求头和请求体的信息,以便正确地传输请求。 ### 回答3: HttpClientJava语言中一个方便的开源HTTP客户端库,用于https请求。它能够实现快速,自由,轻松的实现HTTP请求,可以支持Get、Post、Put、Delete、Head等方法。而POST请求常用于客户端提交数据给服务器端,接着进行处理,故HttpClient发送POST请求是非常重要的。 使用HttpClient发送POST请求主要涉及以下几个方面: 1.构建HttpClient对象:可通过HttpClients.createDefault()方法来创建一个默认的HttpClient实例。 2.构建HttpPost对象:可通过HttpPost(String url)方法来构建一个HttpPost请求体实例。 3.构建Post请求参数:至少需要设置请求体的请求参数。 4.设置请求头:可通过setHeader()方法增加请求头信息,如设置Content-Type和User-Agent等信息。 5.设置请求体:可通过setEntity()方法设置请求体,向服务端传递数据,请求参数类型可为String、ByteArrayEntity、InputStreamEntity、FileEntity等。 6.发送Post请求:可通过提交HttpPost请求来实现向服务端发送POST请求。 以下是HttpClient发送Post请求代码示例: ``` try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost("http://www.xxx.com/post"); httpPost.setHeader("Content-Type", "application/json"); StringEntity stringEntity = new StringEntity("{\"name\":\"test\", \"age\":18}"); httpPost.setEntity(stringEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); System.out.println("responseContent: " + responseContent); } catch (Exception e) { e.printStackTrace(); } ``` 该示例中通过HttpPost(String url)方法构建HttpPost请求实例,并设置请求头信息,如Content-Type和User-Agent等。然后通过StringEntity(String str)方法将JSON格式的请求参数字符串设置到请求体中。最后通过httpClient.execute(httpPost)方法提交HttpPost请求,接收服务端返回的HttpResponse响应实例,并通过EntityUtils.toString()方法获取响应内容。 总结:HttpClient发送POST请求主要是通过构建HttpPost实例对象,设置请求头和请求体参数,最后提交HttpPost请求向服务器发送POST请求,可以方便的实现与服务端的数据交互。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值