HttpClient的使用

一、初识HttpClient

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

二、HttpClient使用

使用之前,需要导入maven坐标,不使用maven就要自己取下jar包,apache官网就有。

   <dependency>
       <groupId>commons-httpclient</groupId>
       <artifactId>commons-httpclient</artifactId>
       <version>3.1</version>
   </dependency>

使用下列工具类即可完成HTTP的请求

public class HttpClientUtil{
    /**
     * 发送TFS get请求
     *
     * @param url
     * @param apiAuthString
     * @return
     */
    public static String sendGet(String url, String apiAuthString) {
        String result = null;
        try {
            URL url1 = new URL(url);
            //base加密
            byte[] authEncBytes = Base64.encodeBase64(apiAuthString.getBytes());
            String authStringEnc = new String(authEncBytes);
            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
            InputStream content = (InputStream) connection.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = in.readLine()) != null) {
                result = line;
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发送TFS post请求
     *
     * @param data        参数
     * @param requestUrl    请求地址
     * @param apiAuthString 授权书
     * @return 返回结果
     * @throws IOException
     * @author
     */
    public static String sendPost(JSONObject data, String requestUrl, String apiAuthString)
            throws IOException {

        HttpClient httpClient = new HttpClient();// 客户端实例化
        PostMethod postMethod = new PostMethod(requestUrl);
        byte[] authEncBytes = Base64.encodeBase64(apiAuthString.getBytes());// base加密
        String authStringEnc = new String(authEncBytes);
        // 设置请求头Authorization
        postMethod.setRequestHeader("Authorization", "Basic " + authStringEnc);
        // 设置请求头API_KEY
        //postMethod.setRequestHeader("API_KEY", headerValue);
        // 设置请求头 Content-Type
        postMethod.setRequestHeader("Content-Type", "application/json");//TFS只支持json格式
        postMethod.setRequestHeader("Accept", "api-version=5.1-preview.1");
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(data.toString());
        // 参数编码格式设置防止中文参数乱码
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        // 执行postMethod
        int statusCode = 0;
        try {
            statusCode = httpClient.executeMethod(postMethod);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
        // 301或者302
        if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // 从头中取出转向的地址
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
            return null;
        } else {
            String str = "";
            try {
                str = postMethod.getResponseBodyAsString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return str;
        }

    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

布吉岛01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值