天天看點

URLConnection POST方式傳參總結

URLConnection POST方式傳參總結

HTTP Post方法用于向伺服器送出資料,寫法比Get方法稍微複雜那麼一點,這裡總結一下Post方式傳參的幾種方法

1、  一個或者多個參數,以form形式送出,送出形式如“name=zhangsan&password=123456”,

送出代碼如下(隻是關鍵語句,不是完整代碼):

 URLpostUrl = new URL("your url");

        // 打開連接配接

        HttpURLConnection connection =(HttpURLConnection) postUrl.openConnection();

        // 設定是否向connection輸出,因為這個是post請求,參數要放在

        // http正文内,是以需要設為true

        connection.setDoOutput(true);

        // Read from the connection. Defaultis true.

        connection.setDoInput(true);

        // 預設是 GET方式

       connection.setRequestMethod("POST");

        // Post 請求不能使用緩存

        connection.setUseCaches(false);

       connection.setInstanceFollowRedirects(true);

        // 配置本次連接配接的Content-type,配置為application/x-www-form-urlencoded的

        // 意思是正文是urlencoded編碼過的form參數,下面我們可以看到我們對正文内容使用URLEncoder.encode進行編碼

       connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

        // 連接配接,從postUrl.openConnection()至此的配置必須要在connect之前完成,

        // 要注意的是connection.getOutputStream會隐含的進行connect。

        connection.connect();

        DataOutputStream out = newDataOutputStream(connection

               .getOutputStream());

        // The URL-encoded contend

        // 正文,正文内容其實跟get的URL中 '? '後的參數字元串一緻

        String content = "name=" +URLEncoder.encode("zhangsan", "UTF-8");

        content +="&password="+URLEncoder.encode("123456","UTF-8");;

        // DataOutputStream.writeBytes将字元串中的16位的unicode字元以8位的字元形式寫到流裡面

        out.writeBytes(content);

        out.flush();

        out.close(); 

        BufferedReader reader = newBufferedReader(new InputStreamReader(connection.getInputStream()));

        String line;

        while ((line = reader.readLine()) !=null){

           System.out.println(line);

        }

        reader.close();

        connection.disconnect();

2、  參數以json格式送出,送出方法首先需要把送出的資料對象轉換為json格式字元串,然後送出該字元串,代碼如下(隻是關鍵語句,不是完整代碼):

publicstatic String doPost(String urlPath, String jsonStr) {

        String result = "";

        BufferedReader reader = null;

        try {

            URL url = new URL(urlPath);

            HttpURLConnection conn =(HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");

            conn.setDoOutput(true);

            conn.setDoInput(true);

            conn.setUseCaches(false);

           conn.setRequestProperty("Connection", "Keep-Alive");

            conn.setRequestProperty("Charset","UTF-8");

           conn.setRequestProperty("Content-Type","application/json;charset=UTF-8");

            conn.setRequestProperty("accept","application/json");

            // 往伺服器裡面發送資料

            if (Json != null &&!TextUtils.isEmpty(jsonStr)) {

                byte[] writebytes =jsonStr.getBytes();

               conn.setRequestProperty("Content-Length",String.valueOf(writebytes.length));

                OutputStream outwritestream =conn.getOutputStream();

                outwritestream.write(jsonStr.getBytes());

                outwritestream.flush();

                outwritestream.close();

            }

            if (conn.getResponseCode() == 200){

                reader = new BufferedReader(

                        newInputStreamReader(conn.getInputStream()));

                result = reader.readLine();

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (reader != null) {

                try {

                    reader.close();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }

        return result;

    }

另外,關于何時使用BufferReader.read()和BufferReader.readLine()方法,可參考如下兩篇部落格:

1、  http://cuisuqiang.iteye.com/blog/1434416#comments

2、   https://www.cnblogs.com/dongrilaoxiao/p/6688107.html

繼續閱讀