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
        //
正文,正文内容其实跟getURL '? '后的参数字符串一致
        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

猜你喜欢

转载自blog.csdn.net/baidu_27196493/article/details/79758706