Post設置請求參數的 a、b、c三個 步驟
a:聲明List集合封裝表單參數
b:創建表單的entity對象
c:設定表單獨的entity到httpPost請求中
完整代碼
/**設置postMan帶參數的Post方式請求
* @version 1.0.0
* @program: recuit_gather
* @description:
* @author: zhangdaxu
* @create: 2020-03-13 17:52
*/
public class httpClientPostParam07Test {
@Test
public void getParam() throws URISyntaxException, UnsupportedEncodingException {
System.out.println("設置postMan帶參數的Post方式請求");
//1:創建httpClient對象
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://yun.itheima.com");
System.out.println("http請求信息:"+httpPost); //返回值: http請求信息: GET http://www.itcast.cn HTTP/1.1
//設置請求參數 a、b、c三個 步驟
//a:聲明List集合封裝表單參數
//b:創建表單的entity對象
//c:設定表單獨的entity到httpPost請求中
//a:聲明List集合封裝表單參數
//聲名集合:NameValuepair 是名值對。
List<NameValuePair> parms = new ArrayList<NameValuePair>();
//向集合中添加對象
parms.add(new BasicNameValuePair("keys","Java"));
//b:創建表單的entity對象
//創建表單獨的Entity對象,第一個參數是封裝好的表單數據,第二個是數據的編碼
UrlEncodedFormEntity formEntity= new UrlEncodedFormEntity(parms,"utf8");
//c:設定表單獨的entity到httpPost請求中
httpPost.setEntity(formEntity);
// 3:設置請求響應的接收變量,如內容為主及必要信息(host,API,HTTP code,響應code,響應時間等等記錄)。
CloseableHttpResponse response=null;
try {
response= httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode()==200){
//把得到響應的載體內容,傳遞給變量content
String content = EntityUtils.toString(response.getEntity(), "utf8");
//輸出響應內容的長度,暫不輸出
System.out.println("響應得到內容長度為:"+content.length());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//擴散閱讀
定義了一個list,該list的數據類型是NameValuePair(簡單名稱值對節點類型),這個代碼多處用於Java像url發送Post請求。在發送post請求時用該list來存放參數。
發送請求的大致過程如下:
String url="http://www.baidu.com";
HttpPost httppost=new HttpPost(url); //建立HttpPost對象
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一個NameValuePair數組,用於存儲欲傳送的參數
params.add(new BasicNameValuePair("pwd","2544"));
//添加參數
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//設置編碼
HttpResponse response=new DefaultHttpClient().execute(httppost);
//發送Post,並返回一個HttpResponse對象
發送請求的大致過程如下:
String url="http://www.baidu.com";
HttpPost httppost=new HttpPost(url); //建立HttpPost對象
List<NameValuePair> params=new ArrayList<NameValuePair>();
//建立一個NameValuePair數組,用於存儲欲傳送的參數
params.add(new BasicNameValuePair("pwd","2544"));
//添加參數
httppost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//設置編碼
HttpResponse response=new DefaultHttpClient().execute(httppost);
//發送Post,並返回一個HttpResponse對象