Android之用HTTP的get,post,HttpClient三種方式向service提交文本資料
來源:互聯網
上載者:User
/** * HTTP請求 * @author kesenhoo * */ public class HttpRequest { public static boolean sendXML(String path, String xml)throws Exception { byte[] data = xml.getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); //如果通過post提交資料,必須設定允許對外輸出資料 conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(data); outStream.flush(); outStream.close(); if(conn.getResponseCode()==200) { return true; } return false; } /** * 通過get方式提交參數給伺服器 * @param path * @param params * @param enc * @return * @throws Exception */ public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception { //構造如下形式的字串,這裡的字串依情況不同 // ?method=save&title=435435435&timelength=89& //使用StringBuilder對象 StringBuilder sb = new StringBuilder(path); sb.append('?'); //迭代Map for(Map.Entry<String, String> entry : params.entrySet()) { sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); //開啟連結 URL url = new URL(sb.toString()); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); //如果請求響應碼是200,則表示成功 if(conn.getResponseCode()==200) { return true; } return false; } /** * 通過Post方式提交參數給伺服器 * @param path * @param params * @param enc * @return * @throws Exception */ public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception { //需要構造的字串形式如下: // title=dsfdsf&timelength=23&method=save StringBuilder sb = new StringBuilder(); //如果參數不為空白 if(params!=null && !params.isEmpty()) { for(Map.Entry<String, String> entry : params.entrySet()) { //Post方式提交參數的話,不能省略內容類型與長度 sb.append(entry.getKey()).append('=') .append(URLEncoder.encode(entry.getValue(), enc)).append('&'); } sb.deleteCharAt(sb.length()-1); } //得到實體的位元據 byte[] entitydata = sb.toString().getBytes(); URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(5 * 1000); //如果通過post提交資料,必須設定允許對外輸出資料 conn.setDoOutput(true); //這裡只設定內容類型與內容長度的頭欄位 //內容類型Content-Type: application/x-www-form-urlencoded //內容長度Content-Length: 38 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length)); OutputStream outStream = conn.getOutputStream(); //把實體資料寫入是輸出資料流 outStream.write(entitydata); //記憶體中的資料刷入 outStream.flush(); outStream.close(); //如果請求響應碼是200,則表示成功 if(conn.getResponseCode()==200) { return true; } return false; } /** * 在遇上HTTPS安全模式或者操作cookie的時候使用HTTPclient會方便很多 * 使用HTTPClient(開源項目)向伺服器提交參數 * @param path * @param params * @param enc * @return * @throws Exception */ public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception { //需要把參數放到NameValuePair List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(); if(params!=null && !params.isEmpty()) { for(Map.Entry<String, String> entry : params.entrySet()) { paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } //對請求參數進行編碼,得到實體資料 UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc); //構造一個請求路徑 HttpPost post = new HttpPost(path); //佈建要求實體 post.setEntity(entitydata); //瀏覽器對象 DefaultHttpClient client = new DefaultHttpClient(); //執行post請求 HttpResponse response = client.execute(post); //從狀態行中擷取狀態代碼,判斷響應碼是否符合要求 if(response.getStatusLine().getStatusCode()==200) { return true; } return false; } }