java http发送post请求

java http发送post请求

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

package xxx.common;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;

public class HttpTool {

    /**
     * 发送post请求
     *
     * @param params        参数
     * @param requestUrl    请求地址
     * @return 返回结果
     * @throws IOException
     */
    public static String sendPost(String params, String requestUrl,
                                  String authorization) throws IOException {
        // 将参数转为二进制流
        byte[] requestBytes = params.getBytes("utf-8");
        // 客户端实例化
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(requestUrl);
        //设置请求头Authorization
        //postMethod.setRequestHeader("Authorization", "Basic " + authorization);
        // 设置请求头 Content-Type
        postMethod.setRequestHeader("Content-Type", "application/json");
        InputStream inputStream = new ByteArrayInputStream(requestBytes, 0,
                requestBytes.length);
        // 请求体
        RequestEntity requestEntity = new InputStreamRequestEntity(inputStream,
                requestBytes.length, "application/json; charset=utf-8");
        postMethod.setRequestEntity(requestEntity);
        // 执行请求
        httpClient.executeMethod(postMethod);
        // 获取返回的流
        InputStream soapResponseStream = postMethod.getResponseBodyAsStream();
        byte[] datas = null;
        try {
            // 从输入流中读取数据
            datas = readInputStream(soapResponseStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String result = new String(datas, "UTF-8");// 将二进制流转为String
        // 打印返回结果
        //System.out.println(result);
        return result;

    }

    /**
     * 从输入流中读取数据
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值