1. 程式人生 > >呼叫介面的2中方法(conn和httpclient)

呼叫介面的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();
    }
}