http post请求

1.引入所需要的jar包

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

2.编写工具类(JSON格式)

package com.springmvc.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpPostUtil {
    public static String doPost(String url, String bodyJson){
        //创建CloseableHttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();

        //创建HttpPost对象
        HttpPost httpPost = new HttpPost(url);

        //设置请求参数
        httpPost.setEntity(new StringEntity(bodyJson, "utf-8"));

        //调用CloseableHttpClient对象的execute(),发送请求
        CloseableHttpResponse response = null;
        String result = "";
        try {
            response = client.execute(httpPost);
            //调用CloseableHttpResponse对象的getEntity(),获得HttpEntity对象,该对象包装了服务器的响应内容
            HttpEntity entity = response.getEntity();
            //获取返回的参数
            result = EntityUtils.toString(entity);
            return result;
        }catch (Exception e){
            System.out.println("发送post失败");
        }finally {
            if (client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值