1. 程式人生 > >Android使用HttpURLConnection進行POST請求,向伺服器上傳資料

Android使用HttpURLConnection進行POST請求,向伺服器上傳資料

先在清單檔案中需要新增許可權:

<uses-permission android:name="android.permission.INTERNET"/>  

開始使用HttpURLConnection進行POST請求,向伺服器上傳資料:
(1)定位到要獲取資源的網址並開啟連線:

URL url = new URL(String urlPath);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

(2)進行連線設定:

//設定連線超時,2000ms
httpURLConnection.setConnectTimeout(2000
); //設定指定時間內伺服器沒有返回資料的超時,5000ms httpURLConnection.setReadTimeout(5000); //設定允許輸出 httpURLConnection.setDoOutput(true); //設定請求的方式 httpURLConnection.setRequestMethod("POST");

(3)將要傳送的資料寫入輸出流:

PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
out.print(timeTag);//寫入輸出流
out.flush();//立即重新整理

out
.close();

(4)對響應碼進行判斷,並獲取網路返回的輸入流:

int code = httpURLConnection.getResponseCode();
if(code == 200){
     InputStream is = httpURLConnection.getInputStream();
     //連線伺服器後,伺服器做出響應返回的資料
     String serverResponse = URLDecoder.decode(readInStream(is), "utf-8");

     is.close();

    //對返回的資料serverResponse進行操作
}

(5)關閉連線:

httpURLConnection.disconnect();

一個向伺服器上傳Json資料包的例子:

    /**
     * 將Json物件上傳伺服器
     * @param url
     * @param jsonObject
     * @throws JSONException
     */
    private void postJsonToServer(URL url, JSONObject jsonObject ) throws JSONException {

        //把JSON資料轉換成String型別使用輸出流向伺服器寫
        try {
            String str = "user="+ URLEncoder.encode(URLEncoder.encode(String.valueOf(jsonObject), "UTF-8"),"UTF-8");

        try {
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(2000);
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setDoOutput(true);//設定允許輸出
            httpURLConnection.setRequestMethod("POST");//設定請求的方式
            httpURLConnection.setRequestProperty("ser-Agent", "Fiddler");

            //把上面訪問方式改為非同步操作,就不會出現 android.os.NetworkOnMainThreadException異常
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream());
            out.print(str);//寫入輸出流
            out.flush();//立即重新整理

            out.close();


            int code = httpURLConnection.getResponseCode();
            if(code == 200 && ((url.toString()).equals(httpURLConnection.getURL().toString()))){
                //獲取伺服器響應後返回的資料
                InputStream is = httpURLConnection.getInputStream();
                String successResponse = URLDecoder.decode(readInStream(is), "utf-8");
                is.close();

              if(SUCCESS_RESPONSE.equals(successResponse)){

                    //上傳成功
                }

            } else{

                //上傳失敗
            }

        }catch (ConnectException e){
            e.printStackTrace();
        }

        catch (SocketTimeoutException e){
            e.printStackTrace();

        catch (IOException e) {
            e.printStackTrace();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }