1. 程式人生 > 實用技巧 >java httpclient介面自動化

java httpclient介面自動化

環境準備:

idea 在pom檔案中引入依賴包

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

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

先初始化一些引數和例項

String url;  //請求地址
CloseableHttpClient httpClient; //用來發送http請求的HttpClient例項
CloseableHttpResponse httpResponse; //用來接受響應資訊的例項
String responseBody; //儲存響應主體

建立get請求:

//建立一個httpClient的例項  
httpClient = HttpClients.createDefault();  
//建立一個httpGet請求例項
HttpGet httpGet = new HttpGet(url);  
//使用httpClient例項傳送剛建立的get請求,並用httpResponse將反饋接收
httpResponse = httpClient.execute(httpGet);
//處理響應
HttpEntity entity = httpResponse.getEntity();
responseBody = EntityUtils.toString(entity,"tuf-8");

建立post請求:

//建立一個httpClient的例項  
httpClient = HttpClients.createDefault();  
//建立一個httpGet請求例項
HttpPost httpPost = new HttpPost(url);  
//新增引數params
Map<String, String> params = new
HashMap<String, String>(); params.put("username","ceshi1"); params.put("password","123456"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //建立引數佇列 for (Map.Entry<String, String> entry : params.entrySet()) { formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } post.setEntity(new UrlEncodedFormEntity(formParams, "utf-8")); //使用httpClient例項傳送剛建立的get請求,並用httpResponse將反饋接收 httpResponse = httpClient.execute(httpPost); //處理響應 HttpEntity entity = httpResponse.getEntity(); responseBody = EntityUtils.toString(entity,"utf-8");