轉自:
http://www.java265.com/JavaCourse/202204/2937.html
HttpClient是一個java語言撰寫的包,
我們使用HttpClient可以非常方便的發送Http請求
它使基于Http協議請求內容變得非常簡單
HttpClient是Apache Jakarta Common下的子專案 它里面封裝了很多使用http協議訪問的工具,可用于高效訪問http
下文筆者講述基于HttpClient Utils工具類撰寫一個表單提交的示例分享,如下所示:
HttpClient Utils進行表單提交同post提交的方式一摸一樣,如下所示
實作思路:
1.獲取連接
2.宣告一個HttpPost
3.創建請求引數體
4.execute獲取資訊
5.getEntity獲取回傳資訊
6.關閉連接
/**
* post方式提交表單(模擬用戶登錄請求)
*/
public void postForm() {
// 創建默認的httpClient實體.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建httppost
HttpPost httppost = new HttpPost("http://java265.com/login");
// 創建引數佇列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "java265.compwd"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500096.html
標籤:其他
上一篇:C++多型性
下一篇:Python Json使用
