Java http发送post请求

使用org.apche.commons.httpclient工具包

maven地址
<dependency>
    <groupId>org.kie.modules</groupId>
    <artifactId>org-apache-commons-httpclient</artifactId>
    <version>6.2.0.CR2</version>
</dependency>
实现代码
public class HttpTool{
    public static void httpPost() throes Exception{
        //请求内容	json格式的参数,可以将我们要发送的内容转换为json格式
        String paramsJson = "";
        
        /*服务端通常是根据请求头(headers)中的Content-Type字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。所以说到POST提交数据方案,包含了Content-Type和消息主体编码方式两部分*/
        
        //客户端实例化
        HttpClient client = new HttpClient();
        
        //请求方法post,可以将请求路径传入构造参数中
        PostMethod postMethod = new PostMethod("http://...");
        
        //设置请求头
        postMethod.addRequestHeader("Content-type","application/json;charset=utf-8");
        
        //将参数转为二进制
        byte[] requestBytes = paramsJson.getBytes("utf-8");
        InputStream inputStream = new ByteArrayInputStream(requestBytes,0,requestBytes.length);
        //设置请求体
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,requestBytes.length,"application/json;charset=utf-8");
        
        //执行方法	这里可以根据请求状态判断请求是否成功,然后根据第三方接口返回的数据格式,解析出我们需要的数据
        int i = client.executeMethod(postMethod);
        
        
        //得到响应数据
        byte[] responseBody = postMethod.getResponseBody();
        String s = new String(responseBody);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值