httpclient 之get方法(無參和有參)


httplient 執行接口測試,采用maven項目,pom.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>httpclient</groupId>
<artifactId>httpclient</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-cache</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.6</version>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20140107</version>
</dependency>
</dependencies>


</project>

 

httpclient 之get方法(無參和有參)

package httpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import org.json.JSONObject;
/**
* Created by jiangcui on 2018/5/18.
*/
public class HttpclientGet {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
//String html = "";
String url1 = "http://www.baidu.com";
String url2 = "http://www.sina.com";

//發送get請求
HttpGet httpGet = new HttpGet(url1);

//設置了header 的參數,如果不需要,可以省略
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "*/*");
headers.put("Accept-Encoding", "gzip, deflate, sdch");
headers.put("Accept-Language", "zh-CN,zh;q=0.8");

for (Map.Entry m : headers.entrySet()) {
System.out.println(m.getKey() + "\t" + m.getValue());
httpGet.setHeader(m.getKey().toString(), m.getValue().toString());
}
//配置請求超時設置
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000) //設置連接超時時間
.setConnectionRequestTimeout(5000) // 設置連接請求超時時間
.setSocketTimeout(5000)
.setRedirectsEnabled(true) //設置自動允許重定向
.build();
httpGet.setConfig(requestConfig);

//獲取 response內容
try {
CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpGet);
//獲取響應狀態碼
int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
System.out.println(statusCode);

if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity = closeableHttpResponse.getEntity();
String strResult = EntityUtils.toString(httpEntity);
System.out.println(strResult);
// 把字符串轉換為json對象
JSONObject jsonObject = new JSONObject(strResult);
System.out.println(jsonObject);
} else {
String strResult = "Error Response: " + closeableHttpResponse.getStatusLine().toString();
System.out.println(strResult);
}

} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}

//CloseableHttpClient httpClient2 = HttpClients.createDefault();

//封裝參數,get方法傳遞參數
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username", "jiangcui"));
param.add(new BasicNameValuePair("password", "pdmi1234"));

try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(param, "utf-8");
String str = EntityUtils.toString(urlEncodedFormEntity);
System.out.println(str);
}catch(IOException e){
e.printStackTrace();
}
}

try{
//創建httpGet請求
HttpGet httpGet2 = new HttpGet(url2);

//執行httpGet請求
CloseableHttpResponse closeableHttpResponse1 = httpClient.execute(httpGet2);
int statusCode = closeableHttpResponse1.getStatusLine().getStatusCode();
System.out.println(statusCode);


if (closeableHttpResponse1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity httpEntity1 = closeableHttpResponse1.getEntity();
String strResult1 = EntityUtils.toString(httpEntity1);
System.out.println(strResult1);
// 把字符串轉換為json對象
JSONObject jsonObject = new JSONObject(strResult1);
//獲取json串中的數據
//String str = jsonObject.get("name").toString;

//將json對象轉化為字符串
String jsonToString = jsonObject.toString();
System.out.println(jsonToString);
} else {
String strResult = "Error Response: " + closeableHttpResponse1.getStatusLine().toString();
System.out.println(strResult);
}
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


免責聲明!

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



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