HttpClient Post請求

HttpClient Post請求

doPost(null, "https://www.baidu.com/");

 

/**
* 訪問數據庫並返回JSON數據字符串

* @param params
* 向服務器端傳的參數
* @param url
* @return
* @throws Exception
*/
public static String doPost(List<NameValuePair> params, String url)
throws Exception {
String result = null;
// 獲取HttpClient對象
HttpClient httpClient = new DefaultHttpClient();
// 新建HttpPost對象
HttpPost httpPost = new HttpPost(url);
if (params != null) {
// 設置字符集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 設置參數實體
httpPost.setEntity(entity);
}
// 連接超時
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
// 請求超時
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
3000);
// 獲取HttpResponse實例
HttpResponse httpResp = httpClient.execute(httpPost);
// 判斷是夠請求成功
if (httpResp.getStatusLine().getStatusCode() == 200) {
// 獲取返回的數據
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
} else {
result = null;
}
return result;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章