1.1パートII:リモートインタフェースが呼び出されるのHttpClient
質問:今、私たちは私たちのインターフェースを開発したこと、そしてどのようにこのインタフェースそれを呼び出すには?
A:使用HttpClientをクライアント。
はじめに1.1.1のHttpClient
HTTPClientのは何1.1.1.1
HttpClientは、効率的な、新しい、機能豊富なクライアントのサポートHTTPプロトコルのプログラミングツールキットを提供するようにApacheジャカルタ共通のサブプロジェクトであり、それはHTTPプロトコルと勧告の最新バージョンをサポートしています。これは、HTTPのすべてのメソッド(GET、POST、PUT、HEAD、など)を実装します
ダウンロード:http://hc.apache.org/
1.1.1.2 HTTPClientの役割
HTTPリクエストを送信するJavaコード、。典型的には、リモートインターフェース呼び出しを実装するために使用されます。
1.1.2 HttpClientをテスト
説明:で自我ベースのテスト
自我ベースのプロジェクトに依存POMのHTTPClientを追加します。
<依存> <groupIdを> org.apache.httpcomponents </ groupIdを> <たartifactId> HTTPClientの </たartifactId> </依存関係> |
GETリクエストを実行する1.1.2.1
パブリック 静的 ボイドのdoGet(){ //作成HttpClientをオブジェクト CloseableHttpClientのHTTPClient = HttpClients。createDefault();
//作成HTTP GETリクエストを HTTPGET HTTPGET = 新 HTTPGET( "http://www.oschina.net/");
CloseableHttpResponse応答= nullを。 してみてください { //実行要求 応答= httpclient.execute(HTTPGET)。 システム。アウト .println(response.getStatusLine()); //状態が200を返されているか否かを判定する もし(response.getStatusLine()。getStatusCode()== 200){ 文字列の内容= EntityUtils。toString(response.getEntity()、 "UTF-8"); 。システムOUT .println( "のContent-Length:" + content.length()); } } キャッチ(例外e){ e.printStackTrace();
} 最後に { もし(レスポンス!= nullの){ してみてください { response.close(); } キャッチ(IOExceptionを電子){ e.printStackTrace(); } } してみてください { httpclient.close(); } キャッチ(IOExceptionを電子){ e.printStackTrace(); } } |
1.1.2.2は、GETパラメータを実行します
パブリック 静的 ボイド doGetParam(){ //オブジェクトを作成します。HttpClientを CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = null; try {
// 定义请求的参数 URI uri = new URIBuilder("http://www.baidu.com/s").setParameter("wd", "数据库").build();
System.out.println(uri);
// 创建http GET请求 HttpGet httpGet = new HttpGet(uri);
// 执行请求 response = httpclient.execute(httpGet); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } }catch(Exception e){ e.printStackTrace();
}finally { if (response != null) { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
1.1.2.3 执行post请求
public static void doPost(){ // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
// 创建http POST请求 HttpPost httpPost = new HttpPost("http://www.oschina.net/");
CloseableHttpResponse response = null; try { // 执行请求 response = httpclient.execute(httpPost); System.out.println(response.getStatusLine()); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } }catch(Exception e){ e.printStackTrace();
}finally { if (response != null) { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
1.1.2.4 执行post带参数
public static void doPostParam() throws Exception{ // 创建Httpclient对象 CloseableHttpClient httpclient = HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
// 创建http POST请求 HttpPost httpPost = new HttpPost("http://www.oschina.net/search");
// 设置2个post参数,一个是scope、一个是q List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("scope", "project")); parameters.add(new BasicNameValuePair("q", "java")); // 构造一个form表单式的实体 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters); // 将请求实体设置到httpPost对象中 httpPost.setEntity(formEntity);
CloseableHttpResponse response = null; try { // 执行请求 response = httpclient.execute(httpPost); System.out.println(response.getStatusLine()); // 判断返回状态是否为200 if (response.getStatusLine().getStatusCode() == 200) { String content = EntityUtils.toString(response.getEntity(), "UTF-8"); System.out.println(content); } } finally { if (response != null) { response.close(); } httpclient.close(); } } |
1.1.3 httpclient常见问题及解决方案
1.1.3.1 请求参数乱码
设置请求的编码格式:
obj.addHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8"); |
1.1.3.2 响应HTTP/1.1 403 Forbidden
原因:网站设置了反爬虫机制,禁止非法访问。
解决方案:伪装浏览器。
obj.addHeader("User-Agent"," Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537. 36 (KHTML, like Gecko) Chrome/31.0.1650.63")
|