java實現利用httpclient訪問接口


HTTP協議時Internet上使用的很多也很重要的一個協議,越來越多的java應用程序需要通過HTTP協議來訪問網絡資源。 
HTTPClient提供的主要功能:

1、實現了所有HTTP的方法(GET、POST、等PUT、HEAD); 
2、支持自動轉向; 
3、支持HTTPS協議; 
4、支持代理服務器等。

使用HttpClient需要以下6個步驟:

  1. 創建HttpClient的實例
  2. 創建某種連接方法的實例,GetMethod/PostMethod。在 GetMethod/PostMethod的構造函數中傳入待連接的地址
  3. 調用第一步中創建好的實例的 execute 方法來執行第二步中創建好的 method 實例
  4. 讀response
  5. 釋放連接。無論執行方法是否成功,都必須釋放連接
  6. 對得到后的內容進行處理

 





java實現利用httpclient訪問接口

利用枚舉先new 四種訪問方式

package util;
 
import org.apache.http.client.methods.*;
 
/**
 * @author jreffchen
 */
public enum HttpRequestMethedEnum {
    // HttpGet請求
    HttpGet {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpGet(url); }
    },
    // HttpPost 請求
    HttpPost {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpPost(url); }
    },
    // HttpPut 請求
    HttpPut {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpPut(url); }
    },
    // HttpDelete 請求
    HttpDelete {
        @Override
        public HttpRequestBase createRequest(String url) { return new HttpDelete(url); }
    };
 
    public HttpRequestBase createRequest(String url) { return null; }
}

寫一個HttpClientUtil通用類

package util;
 
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.*;
import org.apache.http.entity.ContentType;
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 java.io.IOException;
import java.util.Map;
 
/**
 * @author jreffchen
 */
public class HttpClientUtil {
 
    /**
     * httpclient使用步驟
     * 1、創建一個HttpClient對象;
     * 2、創建一個Http請求對象並設置請求的URL,比如GET請求就創建一個HttpGet對象,POST請求就創建一個HttpPost對象;
     * 3、如果需要可以設置請求對象的請求頭參數,也可以往請求對象中添加請求參數;
     * 4、調用HttpClient對象的execute方法執行請求;
     * 5、獲取請求響應對象和響應Entity;
     * 6、從響應對象中獲取響應狀態,從響應Entity中獲取響應內容;
     * 7、關閉響應對象;
     * 8、關閉HttpClient.
     */
 
    private static RequestConfig requestConfig = RequestConfig.custom()
            //從連接池中獲取連接的超時時間
            // 要用連接時嘗試從連接池中獲取,若是在等待了一定的時間后還沒有獲取到可用連接(比如連接池中沒有空閑連接了)則會拋出獲取連接超時異常。
            .setConnectionRequestTimeout(15000)
            //與服務器連接超時時間:httpclient會創建一個異步線程用以創建socket連接,此處設置該socket的連接超時時間
            //連接目標url的連接超時時間,即客服端發送請求到與目標url建立起連接的最大時間。超時時間3000ms過后,系統報出異常
            .setConnectTimeout(15000)
            //socket讀數據超時時間:從服務器獲取響應數據的超時時間
            //連接上一個url后,獲取response的返回等待時間 ,即在與目標url建立連接后,等待放回response的最大時間,在規定時間內沒有返回響應的話就拋出SocketTimeout。
            .setSocketTimeout(15000)
            .build();
 
 
    /**
     * 發送http請求
     *
     * @param requestMethod 請求方式(HttpGet、HttpPost、HttpPut、HttpDelete)
     * @param url 請求路徑
     * @param params post請求參數
     * @param header 請求頭
     * @return 響應文本
     */
    public static String sendHttp(HttpRequestMethedEnum requestMethod, String url, Map<String, Object> params, Map<String, String> header) {
        //1、創建一個HttpClient對象;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        String responseContent = null;
        //2、創建一個Http請求對象並設置請求的URL,比如GET請求就創建一個HttpGet對象,POST請求就創建一個HttpPost對象;
        HttpRequestBase request = requestMethod.createRequest(url);
        request.setConfig(requestConfig);
        //3、如果需要可以設置請求對象的請求頭參數,也可以往請求對象中添加請求參數;
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                request.setHeader(entry.getKey(), entry.getValue());
            }
        }
        // 往對象中添加相關參數
        try {
            if (params != null) {
                ((HttpEntityEnclosingRequest) request).setEntity(
                        new StringEntity(JSON.toJSONString(params),
                                ContentType.create("application/json", "UTF-8")));
            }
            //4、調用HttpClient對象的execute方法執行請求;
            httpResponse = httpClient.execute(request);
            //5、獲取請求響應對象和響應Entity;
            HttpEntity httpEntity = httpResponse.getEntity();
            //6、從響應對象中獲取響應狀態,從響應Entity中獲取響應內容;
            if (httpEntity != null) {
                responseContent = EntityUtils.toString(httpEntity, "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //7、關閉響應對象;
                if (httpResponse != null) {
                    httpResponse.close();
                }
                //8、關閉HttpClient.
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }
}

最后,單元測試

Get請求:

/**
 * 獲取流程定義列表
 * @throws UnsupportedEncodingException 轉碼異常
 */
@Test
public void getProcessDefinitionList() throws UnsupportedEncodingException {
    String url = "http://127.0.0.1:8080/activiti-rest/service/repository/process-definitions";
 
    // 存儲相關的header值

Map<String,String> header = new HashMap<String, String>(); //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8")); header.put("Authorization", "Basic " + encoding); String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpGet,url, null,header); System.out.println(JSON.toJSONString(JSONObject.parseObject(response),true)); }

Post請求:

/**
 * 歷史流程實例列表(以post方式,推薦)
 * @throws UnsupportedEncodingException 轉碼異常
 */
@Test
public void postHistoryProcessInstancesList() throws UnsupportedEncodingException {
    String url = "http://127.0.0.1:8080/activiti-rest/service/query/historic-process-instances";
 
    // 存儲相關的header值
    Map<String,String> header = new HashMap<String, String>();
    //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token
    String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8"));
    header.put("Authorization", "Basic " + encoding);
 
    // 相關請求參數
    Map<String,Object> params = new HashMap<String, Object>();
    params.put("processDefinitionKey", "process");
 
    String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpPost,url,params, header);
    System.out.println(JSON.toJSONString(JSONObject.parseObject(response),true));
}

Put請求

/**
 * 更新任務
 *
 * @throws UnsupportedEncodingException 轉碼異常
 */
@Test
public void putProcessRuntimeTask() throws UnsupportedEncodingException {
    String url = "http://127.0.0.1:8080/activiti-rest/service/runtime/tasks/50019";
 
    // 存儲相關的header值
    Map<String, String> header = new HashMap<String, String>();
    //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token
    String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8"));
    header.put("Authorization", "Basic " + encoding);
 
    // 存儲相關的params值
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("assignee", "zhangsan");
 
    String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpPut, url, params, header);
    System.out.println(JSON.toJSONString(JSONObject.parseObject(response), true));
}
Delete請求
/**
 * 刪除任務的一個IdentityLink
 *
 * @throws UnsupportedEncodingException 轉碼異常
 */
@Test
public void deleteProcessRuntimeIdentityLink() throws UnsupportedEncodingException {
    String url = "http://127.0.0.1:8080/activiti-rest/service/runtime/tasks/50014/identitylinks/users/wangwu/candidate";
 
    // 存儲相關的header值
    Map<String, String> header = new HashMap<String, String>();
    //username:password--->訪問的用戶名,密碼,並使用base64進行加密,將加密的字節信息轉化為string類型,encoding--->token
    String encoding = DatatypeConverter.printBase64Binary("kermit:kermit".getBytes("UTF-8"));
    header.put("Authorization", "Basic " + encoding);
 
    String response = HttpClientUtil.sendHttp(HttpRequestMethedEnum.HttpDelete, url, null, header);
    System.out.println(JSON.toJSONString(JSONObject.parseObject(response), true));
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM