httpClient 表单提交通用模板

2017-02-23  本文已影响0人  JeniusYang
Java Web中涉及大量的请求调用,常用的方式一般就是RPC和Http两种方式,本篇主要利用Apache的httpClient对表单提交,抽象出一个httpProxy统一适配模板

一. pom依赖

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

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.2.2</version>
</dependency>

二. Java实现

public <T>T httpProxy(String ip,int port,,String url,Map<String,T> requestBody,Map<String,T>headerMap)  
        org.apache.http.HttpHost proxy = new org.apache.http.HttpHost(ip, port);
        url = proxy + url;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = null;
        if (method.equals(Const.GET_METHOD)) { //GET提交
            HttpGet httpGet = new HttpGet(url);

            // 处理请求头
            for (Map.Entry<String, T> map : headerMap.entrySet()) {
                httpGet.setHeader(map.getKey(), map.getValue());
            }
            response = httpClient.execute(httpGet);
        } else if (method.equals(Const.POST_METHOD)) {//POST提交
            HttpPost httpPost = new HttpPost(url);
            /// 处理请求体
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (Map.Entry<String, T> map : requestBody.entrySet()) {
                params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
            }
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            // 处理请求头
            for (Map.Entry<String, T> map : headerMap.entrySet()) {
                httpPost.setHeader(map.getKey(), map.getValue());
            }
            response = httpClient.execute(httpPost);
        } else {
            response = null;
        }

        HttpEntity entity = response.getEntity();
        org.apache.http.Header[] headers = response.getAllHeaders();

        List<org.apache.http.Header> headerList = new ArrayList<org.apache.http.Header>();
        for (org.apache.http.Header header : headers) {
            headerList.add(header);
        }
         int code = response.getStatusLine().getStatusCode();
        InputStream in = entity.getContent();
        String responseBody = IOUtils.toString(in, HTTP.UTF_8);
        httpClient.getConnectionManager().shutdown();

        return new T(code, headerList, responseBody...);
    }

说明:
1. 用泛型代表返回类型可以自行封装
2. form表单提交默认只支持get跟post,其他方式在SpringMVC中需要另加配置http的methodfilter
3. 模板中省去了日志的输出
4. 各个类的源jar不能导错
上一篇下一篇

猜你喜欢

热点阅读