介绍如何使用HttpClient发起GET或者POST请求
<pre name="code" class="java"><span style="font-size:18px;"><span style="color:#3366ff;">/**
* @author Administrator
*
*/</span>
public class HttpUtils {
<span style="color:#009900;">//创建HttpClient对象</span>
public static HttpClient httpClient = new DefaultHttpClient();
<span style="color:#3333ff;">/**
*
* @param url 发送请求的url
* @return 服务器响应字符串
* @throws IOException
* @throws ClientProtocolException
*/</span>
public static String getRequest(String url) throws ClientProtocolException, IOException{
<span style="color:#009900;">//创建HttpGet对象</span>
HttpGet httpGet = new HttpGet(url);
<span style="color:#009900;">//发送GET请求</span>
HttpResponse httpResponse = httpClient.execute(httpGet);
<span style="color:#009900;">//如果服务器成功地返回响应</span>
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return null;
}
<span style="color:#3333ff;">/**
*
* @param url 发送请求的url
* @param rawParams 请求参数
* @return 服务器响应字符串
* @throws ClientProtocolException
* @throws IOException
*/</span>
public static String postRequest(String url,List<NameValuePair> params) throws ClientProtocolException, IOException{
<span style="color:#009900;">//创建HttpPost对象</span>
HttpPost httpPost = new HttpPost(url);
<span style="color:#009900;">//如果传递参数个数较多,可以对传递的参数进行封装</span>
<span style="color:#009900;">// List<NameValuePair> params = new ArrayList<NameValuePair>();
// for(String key:rawParams.keySet()){
// params.add(new BasicNameValuePair(key, rawParams.get(key)));
// }</span>
httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
<span style="color:#009900;">//发送post请求</span>
HttpResponse httpResponse = httpClient.execute(httpPost);
<span style="color:#009900;">//如果服务器成功地返回响应</span>
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return null;
}</span>