Android之用HTTP的get,post,HttpClient三種方式向service提交文本數據


/** 
 * 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;  
    }  
}  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM