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;服務器

}url

相關文章
相關標籤/搜索