HttpClients下載與入門
Http協議的重要性相信不用我多說了,HttpClient相比傳統JDK自帶的URLConnection,增加了易用性和靈活性(具體區別,日后我 們再討論),它不僅是客戶端發送Http請求變得容易,而且也方便了開發人員測試接口(基于Http協議的),即提高了開發的效率,也方便提高代碼的健壯 性。因此熟練掌握HttpClient是很重要的必修內容,掌握HttpClient后,相信對于Http協議的了解會更加深入。
你可以從官方獲取最新版本:http://hc.apache.org/index.html。也可以從這里獲取官方使用入門示例。
以下示例,輸出所有頭內容,和頁面返回的內容。
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
public class QuickStart {
public static void main(String[] args) {
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://javacui.com");
CloseableHttpResponse response1 = httpclient.execute(httpGet);
try {
System.out.println(response1.getStatusLine()); // 讀取狀態信息
Header[] hd = response1.getAllHeaders(); // 所有頭信息
for(Header h : hd){
System.out.println(h.getName() + ":" + h.getValue());
}
HttpEntity entity1 = response1.getEntity();
System.out.println(EntityUtils.toString(entity1));
} finally {
response1.close();
}
HttpPost httpPost = new HttpPost("http://javacui.com");
List <NameValuePair> paras = new ArrayList <NameValuePair>(); // 設置表單參數
paras.add(new BasicNameValuePair("username", "name"));
paras.add(new BasicNameValuePair("password", "pass"));
httpPost.setEntity(new UrlEncodedFormEntity(paras));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
try {
System.out.println(response1.getStatusLine()); // 讀取狀態信息
Header[] hd = response1.getAllHeaders(); // 所有頭信息
for(Header h : hd){
System.out.println(h.getName() + ":" + h.getValue());
}
HttpEntity entity1 = response1.getEntity();
System.out.println(EntityUtils.toString(entity1));
} finally {
response2.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 讀取流
*/
public static byte[] readStream(InputStream inStream) throws Exception {
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = inStream.read(buffer)) != -1) {
outSteam.write(buffer, 0, len);
}
outSteam.close();
inStream.close();
return outSteam.toByteArray();
}
}
// 結束
GET和POST請求都輸出了獲取到的服務器內容,POST請求設置了請求的表單參數。
本文由用戶 xg48 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!