Android_HttpClient_get請求post表單提交上傳

關於HttpUrlConnection用法

1.HttpRequestBase(HttpGet..)

HttpClient 支持多種訪問網絡的方式,包括GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS. 其對應子類爲HttpGet, HttpHead, HttpPost, HttpPut, HttpDelete, HttpTrace, and HttpOptions.但在使用時多爲HttpGet, HttpPost兩種方式。

[java] 

/** 

 * 一個簡單的get請求 

 */  

private static void get() {  

    // 1.得到HttpClient對象  

    HttpClient httpClient = new DefaultHttpClient();  

    // 2.實例化一個HttpGet對象  

    HttpGet httpGet = new HttpGet("http://www.baidu.com");  

    try {  

        // 3.httpClient執行httpGet請求  

        HttpResponse response = httpClient.execute(httpGet);  

        HttpEntity entity = response.getEntity();  

        if (entity != null) { // 如果有數據表示請求成功  

            System.out.println(EntityUtils.toString(entity, "utf-8"));  

        } else {  

            System.out.println("連接失敗!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 4.釋放資源(Shuts down this connection manager and releases allocated  

        // resources)  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

2.HttpResponse

通過得到HttpResponse對象,可以得到相關訪問網絡的信息,比如getEntity() getStatusLine()等等

[java]  

System.out.println(response.getProtocolVersion());  

System.out.println(response.getStatusLine().getStatusCode());  

System.out.println(response.getStatusLine().getReasonPhrase());  

System.out.println(response.getStatusLine().toString());  

輸出結果爲

[java]  

/* 

HTTP/1.1 

200 

OK 

HTTP/1.1 200 OK 

*/  

[java] 

//得到請求的響應數據  

//方式一.  

HttpEntity entity = response.getEntity();  

if (entity != null) { // 如果有數據表示請求成功  

    System.out.println(EntityUtils.toString(entity, "utf-8"));  

} else {  

    System.out.println("連接失敗!");  

}  

//方式二.  

if(response.getStatusLine().getStatusCode() == 200){  

    HttpEntity myEntity = response.getEntity();  

    BufferedInputStream in = new BufferedInputStream(myEntity.getContent());  

    byte[] bytes = read(in);//通過自定義的read方法,取得該輸入流對應的數據  

}  

3.ResponseHandler

[java]  

/** 

 * 通過ResponseHandler處理請求 

 */  

private static void test() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpGet httpGet = new HttpGet("http://www.baidu.com");  

      

    //自定義ResponseHandler對象  

    ResponseHandler<String> myHandler = new ResponseHandler<String>() {  

        @Override  

        public String handleResponse(HttpResponse response)  

                throws ClientProtocolException, IOException {  

            HttpEntity entity = response.getEntity();  

            String result = "連接失敗!";  

            if (entity != null) { // 如果有數據表示請求成功  

                result = EntityUtils.toString(entity, "utf-8");  

            }  

            return result;  

        }  

    };  

    try {  

        String result = httpClient.execute(httpGet, myHandler);//接收該myHandler對象  

        System.out.println(result);  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

    // 釋放資源(Shuts down this connection manager and releases allocated resources)  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

4.Post完成Form表單的提交

[java] 

/** 

 * 完成form表單的提交 

 */  

private static void post() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/My/upload");  

  

    try {  

        // 爲httpPost設置HttpEntity對象  

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();  

        parameters.add(new BasicNameValuePair("username", "zhangsan"));  

        parameters.add(new BasicNameValuePair("password", "123321"));  

        HttpEntity entity = new UrlEncodedFormEntity(parameters);  

        httpPost.setEntity(entity);  

        // httpClient執行httpPost表單提交  

        HttpResponse response = httpClient.execute(httpPost);  

        // 得到服務器響應實體對象  

        HttpEntity responseEntity = response.getEntity();  

        if (responseEntity != null) {  

            System.out.println(EntityUtils  

                    .toString(responseEntity, "utf-8"));  

            System.out.println("表單上傳成功!");  

        } else {  

            System.out.println("服務器無響應!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 釋放資源  

        httpClient.getConnectionManager().shutdown();  

    }  

}  

5.Post完成文件的長傳

[java] 

/** 

 * 通過post完成文件的上傳 

 */  

private static void postFile() {  

    HttpClient httpClient = new DefaultHttpClient();  

    HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/My/upload");  

    try {  

        // 需要上傳的文件  

        String root = "D:/api/";  

        String fileName = "JDK6.0 中文文檔.CHM";  

        File uploadFile = new File(root+fileName);  

        //定義FileEntity對象  

        HttpEntity entity = new FileEntity(uploadFile);  

        //爲httpPost設置頭信息  

        httpPost.setHeader("filename", URLEncoder.encode(fileName,"utf-8"));//服務器可以讀取到該文件名  

        httpPost.setHeader("Content-Length", String.valueOf(entity.getContentLength()));//設置傳輸長度  

        httpPost.setEntity(entity); //設置實體對象  

          

        // httpClient執行httpPost提交  

        HttpResponse response = httpClient.execute(httpPost);  

        // 得到服務器響應實體對象  

        HttpEntity responseEntity = response.getEntity();  

        if (responseEntity != null) {  

            System.out.println(EntityUtils.toString(responseEntity, "utf-8"));  

            System.out.println("文件 "+fileName+"上傳成功!");  

        } else {  

            System.out.println("服務器無響應!");  

        }  

    } catch (Exception e) {  

        e.printStackTrace();  

    } finally {  

        // 釋放資源  

        httpClient.getConnectionManager().shutdown();  

    }  

}  


轉載地址:http://www.2cto.com/kf/201310/248095.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章