HttpClient中帶參數的get請求


直接代碼:

package cn.itcast.crawler.test;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
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.net.URISyntaxException;

public class HttpGetParamTest {
public static void main(String[] args) throws Exception {
//1.創建HttpClient對象
CloseableHttpClient httpClient= HttpClients.createDefault();
//要求:設置請求的地址是:http://yun.itheima.com/search?keys=java
//創建URLBuilder
URIBuilder uriBuilder=new URIBuilder("http://yun.itheima.com/search");
//設置參數
uriBuilder.setParameter("keys","java");
//2.創建HttpGet對象,設置URL地址
HttpGet httpGet=new HttpGet(uriBuilder.build());
System.out.println("發送請求的信息:"+httpGet);
//使用httpClient發起響應獲取repsonse
CloseableHttpResponse response=null;
try {
response=httpClient.execute(httpGet);
//4.解析響應,獲取數據
//判斷狀態碼是否是200
if(response.getStatusLine().getStatusCode()==200){
HttpEntity httpEntity=response.getEntity();
String content=EntityUtils.toString(httpEntity,"utf8");
System.out.println(content.length());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
}
執行結果:

 

 有上面的結果可以知道,發送的是一個get請求,並且是參數的;

//創建URLBuilder
URIBuilder uriBuilder=new URIBuilder("http://yun.itheima.com/search");
//設置參數
uriBuilder.setParameter("keys","java");
上面兩行代碼是帶參數的主要代碼,這是帶一個參數,當我們需要帶兩個或兩個以上的參數時,代碼如下:
uriBuilder.setParameter("keys","java").setParameter("","");
在后面直接添加就可以了



免責聲明!

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



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