HttpPost方式调用接口通过PostMethod的方式

pom.xml添加依赖包

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>

通过PostMethod的方式(工具类)

package com.topnet.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Base64;

/**
 * TODO
 * 外部接口调用Post
 * @author hejie
 * @date 2021/7/29 17:13
 */
@Slf4j
public class PostMethodUtils {

    /**
     * 发送HttpClient请求
     * @param requestUrl
     * @param params
     * @return
     */
    public static String sendPost(String requestUrl, String params ) {
        InputStream inputStream = null;
        try {
            HttpClient httpClient = new HttpClient();
            PostMethod postMethod = new PostMethod(requestUrl);
            // 设置请求头  Content-Type
            postMethod.setRequestHeader("Content-Type", "application/json");
            RequestEntity requestEntity = new StringRequestEntity(params,"application/json","UTF-8");
            postMethod.setRequestEntity(requestEntity);
            httpClient.executeMethod(postMethod);// 执行请求
            inputStream =  postMethod.getResponseBodyAsStream();// 获取返回的流
            BufferedReader br = null;
            StringBuffer buffer = new StringBuffer();
            // 将返回的输入流转换成字符串
            br = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String temp;
            while ((temp = br.readLine()) != null) {
                buffer.append(temp);
            }
            log.info("接口返回内容为:" + buffer);
            return buffer.toString();
        } catch (Exception e){
            log.info("请求异常" +e.getMessage());
            throw new RuntimeException(e.getMessage());
        } finally {
            if(inputStream != null) {
                try{
                    inputStream.close();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }
}

测试

String parameter = "{ \"dto\":{\"purchaserPhone\":\"13798479813\" }}";
PostMethodUtils.sendPost(requestUrl,parameter);

结果

{
 "status":200,
 "data":[
  {
   "id":10612514,
   "Name":"张三",
   "Dept":520100,
   "DeptCode":"fdrre",
   "DeptName":"贵州",
   "Date":"2020-12-05"
  }
 ]
}

JAVA Http的Post请求传参添加Authorization Basic Auth验证​​​​​​​

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 HttpClient 库来替换旧的 PostMethod 类。下面是一个示例代码,演示如何使用 HttpPost 来发送 POST 请求: ```java import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) throws IOException { String url = "http://example.com/post"; // 创建 HttpClient 实例 HttpClient httpClient = HttpClientBuilder.create().build(); // 创建 HttpPost 请求 HttpPost httpPost = new HttpPost(url); // 设置请求参数 List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("param1", "value1")); params.add(new BasicNameValuePair("param2", "value2")); httpPost.setEntity(new UrlEncodedFormEntity(params)); // 发送请求并获取响应 HttpResponse response = httpClient.execute(httpPost); // 获取响应内容 HttpEntity entity = response.getEntity(); String responseText = EntityUtils.toString(entity); // 打印响应内容 System.out.println(responseText); } } ``` 在上面的示例中,我们首先创建了一个 HttpClient 实例,然后创建了一个 HttpPost 请求,并设置了请求参数。最后,我们使用 HttpClient 发送了 POST 请求,并获取了响应。你可以根据自己的需求修改和扩展这个示例代码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值