先來個傳統的,不過這個里面有些類已經標明 deprecated,所以之后還有更好的方法,起碼沒有被標明 deprecated的類和方法。
前兩個方法是有deprecated的情況。后面用HttpURLConnection 對象的是沒有deprecated的。最后還有個設置代理的方法。就是設置代理了,HttpUrlConnection對象也可以通過 usingProxy 方法判斷是否使用代理了。
/** * 工具包 */ package utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; 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.protocol.HTTP; import org.apache.http.util.EntityUtils; import android.net.Uri; import android.util.Log; import android.view.ViewDebug.FlagToString; /** * 和Htttp相關的類 * * @author Administrator * */ public class HttpUtils { private static final int HTTP_STATUS_OK = 200; /** * 通過post協議發送請求,並獲取返回的響應結果 * * @param url * 請求url * @param params * post傳遞的參數 * @param encoding * 編碼格式 * @return 返回服務器響應結果 * @throws HttpException */ public static String sendPostMethod(String url, Map<String, Object> params, String encoding) throws Exception { String result = ""; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); // 封裝表單 if (null != params && !params.isEmpty()) { List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); for (Map.Entry<String, Object> entry : params.entrySet()) { String name = entry.getKey(); String value = entry.getValue().toString(); BasicNameValuePair pair = new BasicNameValuePair(name, value); parameters.add(pair); } try { // 此處為了避免中文亂碼,保險起見要加上編碼格式 UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity( parameters, encoding); post.setEntity(encodedFormEntity); } catch (UnsupportedEncodingException e) { e.printStackTrace(); Log.d("shang", "UnsupportedEncodingException"); } } try { HttpResponse response = client.execute(post); if (HTTP_STATUS_OK == response.getStatusLine().getStatusCode()) { // 獲取服務器請求的返回結果,注意此處為了保險要加上編碼格式 result = EntityUtils.toString(response.getEntity(), encoding); } else { throw new Exception("Invalide response from API" + response.toString()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 通過get方式發送請求,並返回響應結果 * * @param url * 請求地址 * @param params * 參數列表,例如name=小明&age=8里面的中文要經過Uri.encode編碼 * @param encoding * 編碼格式 * @return 服務器響應結果 * @throws Exception */ public static String sendGetMethod(String url, String params, String encoding) throws Exception { String result = ""; url += ((-1 == url.indexOf("?")) ? "?" : "&") + params; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); get.setHeader("charset", encoding); try { HttpResponse response = client.execute(get); if (HTTP_STATUS_OK == response.getStatusLine().getStatusCode()) { result = EntityUtils.toString(response.getEntity(), encoding); } else { throw new Exception("Invalide response from Api!" + response.toString()); } } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 通過URLConnect的方式發送post請求,並返回響應結果 * * @param url * 請求地址 * @param params * 參數列表,例如name=小明&age=8里面的中文要經過Uri.encode編碼 * @param encoding * 編碼格式 * @return 服務器響應結果 */ public static String sendPostMethod(String url, String params, String encoding) { String result = ""; PrintWriter out = null; BufferedReader in = null; try { URL realUrl = new URL(url); // 打開url連接 HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); // 5秒后超時 conn.setConnectTimeout(5000); // 設置通用的屬性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1"); // post請求必須有下面兩行 conn.setDoOutput(true); conn.setDoInput(true); // post請求不應該使用cache conn.setUseCaches(false); //顯式地設置為POST,默認為GET conn.setRequestMethod("POST"); // 獲取Urlconnection對象的輸出流,調用conn.getOutputStream的時候就會設置為POST方法 out = new PrintWriter(conn.getOutputStream()); // 發送參數 out.print(params); // flush輸出流的緩沖,這樣參數才能發送出去 out.flush(); // 讀取流里的內容,注意編碼問題 in = new BufferedReader(new InputStreamReader( conn.getInputStream(), encoding)); String line = ""; while (null != (line = in.readLine())) { result += line; } } catch (IOException e) { System.out.println("Send post Exection!"); e.printStackTrace(); } finally { // 關閉流 try { if (null != out) { out.close(); } if (null != in) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } return result; } /** * 采用URLConnection的方式發送get請求 * * @param url * 請求地址 * @param params * 參數列表,例如name=小明&age=8里面的中文要經過Uri.encode編碼 * @param encoding * 編碼格式 * @return 服務器響應結果 */ public static String sendGetRequest(String url, String params, String encoding) { String result = ""; BufferedReader in = null; // 連接上參數 url += ((-1 == url.indexOf("?")) ? "?" : "&") + params; try { URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); // 通用設置 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (comptibal; MSIE 6.0; Windows NT 5.1;SV1 )"); // 不使用緩存 conn.setUseCaches(false); // 建立鏈接 conn.connect(); // 獲取所有頭字段 Map<String, List<String>> headers = conn.getHeaderFields(); for (String key : headers.keySet()) { List<String> value = headers.get(key); Log.d("shang", "key=>" + value.toString()); } in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while (null != (line = in.readLine())) { result += line; } } catch (IOException e) { Log.d("shang", "Send get Exception!"); e.printStackTrace(); } finally { if (null != in) { try { in.close(); } catch (IOException e) { Log.d("shang", "BufferReader close Exception!"); e.printStackTrace(); } } } return result; } /** * 設置代理 * * @param ip * 代理ip * @param port * 代理端口號 */ public static void setProxy(String ip, String port) { // 如果不設置,只要代理IP和代理端口正確,此項不設置也可以 System.getProperties().setProperty("http.proxyHost", ip); System.getProperties().setProperty("http.proxyPort", port); } }