调用接口的2中方法(conn和httpclient)

import com.ursa.acf.util.StringUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import org.springframework.stereotype.Service;
import taxis.wzx.APIService;
import taxis.wzx.util.HttpDeleteWithBody;
import taxis.wzx.util.HttpResult;
import taxis.wzx.service.Wzxservice;
import taxis.wzx.util.AESTool;
import taxis.wzx.util.ParseSystemUtil;

 public String getReturnData(String url) throws Exception {
        StringBuffer resultStr = new StringBuffer();
        URL restURL = null;
        try {
            restURL = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

           conn.setRequestProperty("Accept", "application/json");
           conn.setRequestProperty("connection", "Keep-Alive");
           conn.setRequestProperty("user-agent", "Mozilla/4.0(comptibla;MSIE 6.0;Windows NT 5.1;SV1)");
           conn.setRequestProperty("Content-Type", "application/json;Charset=UTF-8");
            //通过接口获取的token(永久有效)
            conn.setRequestProperty("x-access-token",getToken());

            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            int responseCode = conn.getResponseCode();
            if(200 == responseCode){
                InputStream is = conn.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                BufferedReader bReader = new BufferedReader(isr);
                //java.io.BufferedReader br =
                String line = null;
                while (null!=(line=bReader.readLine())){
                    resultStr.append(line);
                }
                is.close();
                isr.close();
                bReader.close();
            }else{
                return "";
            }
            conn.disconnect();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        return   resultStr.toString();
    }

    /**
     * 带参数的get请求
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {
        CloseableHttpClient   httpClient = HttpClients.createDefault();
        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);
        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }
        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        httpGet.setHeader("Accept","application/json");
        httpGet.setHeader("user-agent", "Mozilla/4.0(comptibla;MSIE 6.0;Windows NT 5.1;SV1)");
        httpGet.setHeader("Content-Type", "application/json;Charset=UTF-8");
        httpGet.setHeader("x-access-token","eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIzMjA1MDQxOTczMDUwNjIwMTgiLCJjcmVhdGVkIjoxNTQwOTUyNzY5ODQ5LCJleHAiOjE1NDE1NTc1Njl9.fTBj-5kSomxmsXyCi1w_4uj9cCCP0uj-Jye3sKu-uW0RaDG7wPOtykdOcZSJPW_5WH71_G8F4dELx-3kxIDpCw");
        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = null;
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回
        return httpResult;
    }

    /**
     * 不带参数的get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = this.doGet(url, null);
        return httpResult;
    }

    /**
     * 带参数的post请求
     *
     * @param url
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, JSONObject jsonObject) throws Exception {
        CloseableHttpClient   httpClient = HttpClients.createDefault();
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Accept","*/*");
        httpPost.setHeader("user-agent", "Mozilla/4.0(comptibla;MSIE 6.0;Windows NT 5.1;SV1)");
        httpPost.setHeader("Cache-Control","no-cache");
        httpPost.setHeader("Content-Type", "application/json;Charset=UTF-8");
        httpPost.setHeader("x-access-token",getToken());
        // 判断map不为空
//        if (map != null) {
//            // 声明存放参数的List集合
//            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            // 遍历map,设置参数到list中
//            for (Map.Entry<String, Object> entry : map.entrySet()) {
//                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
//            }
//            // 创建form表单对象
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
//            // 把表单对象设置到httpPost中
//            httpPost.setEntity(formEntity);
//        }
        if(jsonObject!=null){
            StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
        }
        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回结果
        return httpResult;
    }

    /**
     * 不带参数的post请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = this.doPost(url, null);
        return httpResult;
    }

    /**
     * 带参数的Put请求
     *
     * @param url
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public HttpResult doPut(String url, JSONObject jsonObject) throws Exception {
        CloseableHttpClient   httpClient = HttpClients.createDefault();
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("Accept","application/json");
        httpPut.setHeader("user-agent", "Mozilla/4.0(comptibla;MSIE 6.0;Windows NT 5.1;SV1)");
        httpPut.setHeader("Content-Type", "application/json;Charset=UTF-8");
        httpPut.setHeader("x-access-token",getToken());
        // 判断map不为空
//        if (map != null) {
//            // 声明存放参数的List集合
//            List<NameValuePair> params = new ArrayList<NameValuePair>();
//            // 遍历map,设置参数到list中
//            for (Map.Entry<String, Object> entry : map.entrySet()) {
//                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
//            }
//            // 创建form表单对象
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
//            // 把表单对象设置到httpPost中
//            httpPut.setEntity(formEntity);
//        }
        if(jsonObject!=null){
            StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
            entity.setContentType("application/json");
            httpPut.setEntity(entity);
        }
        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = httpClient.execute(httpPut);
        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回结果
        return httpResult;
    }

    /**
     * 带参数的Delete请求
     *
     * @param url
     * @param jsonObject
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, JSONObject jsonObject) throws Exception {
        CloseableHttpClient   httpClient = HttpClients.createDefault();
        // 声明URIBuilder
//        URIBuilder uriBuilder = new URIBuilder(url);
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        if(jsonObject!=null){
            StringEntity entity = new StringEntity(jsonObject.toString(), Charset.forName("UTF-8"));
            entity.setContentType("application/json");
            httpDelete.setEntity(entity);
        }
        // 判断参数map是否为非空
//        if (map != null) {
//            // 遍历参数
//            for (Map.Entry<String, Object> entry : map.entrySet()) {
//                // 设置参数
//                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
//                uriBuilder.setCharset(Charset.forName("UTF-8"));
//            }
//        }
//        // 2 创建httpGet对象,相当于设置url请求地址
//        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
        httpDelete.setHeader("Accept","application/json");
        httpDelete.setHeader("user-agent", "Mozilla/4.0(comptibla;MSIE 6.0;Windows NT 5.1;SV1)");
        httpDelete.setHeader("Content-Type", "application/json;Charset=UTF-8");
        httpDelete.setHeader("x-access-token",getToken());
        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = httpClient.execute(httpDelete);
        // 4 解析结果,封装返回对象httpResult,相当于显示相应的结果
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = null;
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }
        // 返回
        return httpResult;
    }


public class HttpResult {
    //响应的状态码
    private int code;
    //响应的响应体
    private String body;

    public HttpResult(){
    };

    public HttpResult(int code, String body) {
        this.code = code;
        this.body = body;
    }

    public int getCode() {
        return code;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public void setCode(int code) {
        this.code = code;
    }
}

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

import java.net.URI;
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "DELETE";
    @Override
    public String getMethod() {
        return METHOD_NAME;  //To change body of implemented methods use File | Settings | File Templates.
    }

    public HttpDeleteWithBody(final String uri){
        super();
        setURI(URI.create(uri));
    }

    public HttpDeleteWithBody(final URI uri){
        super();
        setURI(uri);
    }

    public HttpDeleteWithBody(){
        super();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27954241/article/details/83780671