Android,HTTP請求類
package com.huahui.uiles;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* Http請求工具類
*
* @author 劉宇
* @date 2014-4-26
*/
public class HttpUtil {
// 創建httpClient對象
public static HttpClient httpClient = new DefaultHttpClient();
/**
*
* @param url
* 發送請求的URL
* @return 服務器響應字符串
* @throws Exception
*/
public static String getRequest(String url) throws Exception {
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(get);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return "HttpGet請求錯誤代碼:" + httpResponse.getStatusLine().getStatusCode();
}
/**
*
* @param url
* 發送請求URL
* @param paramsMap
* 請求參數 這是null則不向服務器提交數據
* @return 服務器響應值
* @throws Exception
*/
public static String postRequest(String url, Map<String, String> paramsMap)
throws Exception {
// 創建HttpPost對象
HttpPost post = new HttpPost(url);
// 如果穿的參數個數較多,可以對傳遞的參數進行封裝
List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
for (String key : paramsMap.keySet()) {
// 封裝請求參數
paramsList.add(new BasicNameValuePair(key, paramsMap.get(key)));
}
// 設置請求參數
post.setEntity(new UrlEncodedFormEntity(paramsList, "UTF-8"));
post.addHeader("Accept", "text/json");
// 發送post請求
HttpResponse httpResponse = httpClient.execute(post);
// 如果成功返回
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 獲取響應字符串
String result = EntityUtils.toString(httpResponse.getEntity());
return result;
}
return "HttpPost請求錯誤代碼:" + httpResponse.getStatusLine().getStatusCode();
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.