Java HttpURLConnection post set params 设置请求参数的三种方法 实践总结


            /**
             * the first way to set  params
             * OutputStream
             */

            byte[] bytesParams = paramsStr.getBytes();
            // 发送请求params参数
            OutputStream outStream=connection.getOutputStream();
            outStream.write(bytesParams);
            outStream.flush();


            /**
             * the second  way  to set  params
             * PrintWriter
             */

             PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
            //PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
            // 发送请求params参数
            printWriter.write(paramsStr);
            printWriter.flush();


            /**
             * the third way to set  params
             * OutputStreamWriter
             */
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            // 发送请求params参数
            out.write(paramsStr);
            out.flush();

demo:

 /**
     * @param pathurl
     * @param paramsStr
     * @return
     */
    private static String postUrlBackStr(String pathurl, String paramsStr) {
        String backStr = "";
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(pathurl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            // 设定请求的方法为"POST",默认是GET
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(50000);
            connection.setReadTimeout(50000);
          // User-Agent  IE11 的标识
            connection.setRequestProperty("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.3; Trident/7.0;rv:11.0)like Gecko");
            connection.setRequestProperty("Accept-Language", "zh-CN");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Charset", "UTF-8");
            /**
             * 当我们要获取我们请求的http地址访问的数据时就是使用connection.getInputStream().read()方式时我们就需要setDoInput(true),
             根据api文档我们可知doInput默认就是为true。我们可以不用手动设置了,如果不需要读取输入流的话那就setDoInput(false)。

             当我们要采用非get请求给一个http网络地址传参 就是使用connection.getOutputStream().write() 方法时我们就需要setDoOutput(true), 默认是false
             */
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            connection.setDoInput(true);
            // 设置是否向httpUrlConnection输出,如果是post请求,参数要放在http正文内,因此需要设为true, 默认是false;
            connection.setDoOutput(true);
            connection.setUseCaches(false);



            /**
             * the first way to set  params
             * OutputStream
             */
         /*   byte[] bytesParams = paramsStr.getBytes();
            // 发送请求params参数
            OutputStream outStream=connection.getOutputStream();
            outStream.write(bytesParams);
            outStream.flush();
            */

            /**
             * the second  way  to set  params
             * PrintWriter
             */
           /* PrintWriter printWriter = new PrintWriter(connection.getOutputStream());
            //PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"UTF-8"));
            // 发送请求params参数
            printWriter.write(paramsStr);
            printWriter.flush();*/

            /**
             * the third way to set  params
             * OutputStreamWriter
             */
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8");
            // 发送请求params参数
            out.write(paramsStr);
            out.flush();


            connection.connect();//
            int contentLength = connection.getContentLength();
            if (connection.getResponseCode() == 200) {
                inputStream = connection.getInputStream();//会隐式调用connect()
                baos = new ByteArrayOutputStream();
                int readLen;
                byte[] bytes = new byte[1024];
                while ((readLen = inputStream.read(bytes)) != -1) {
                    baos.write(bytes, 0, readLen);
                }
                backStr = baos.toString();
                Log.i(TAG, "backStr:" + backStr);

            } else {
                Log.e(TAG, "请求失败 code:" + connection.getResponseCode());
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return backStr;
    }
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Java提供的HttpURLConnection或者Apache HttpClient库来实现POST请求提交JSON参数。 使用HttpURLConnection实现POST请求提交JSON参数的示例代码如下: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 添加请求头 con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); // 发送POST请求 con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write(json.getBytes("UTF-8")); os.flush(); os.close(); // 获取返回结果 int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印返回结果 System.out.println(response.toString()); } } ``` 使用Apache HttpClient库实现POST请求提交JSON参数的示例代码如下: ```java import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.HttpResponse; import java.io.BufferedReader; import java.io.InputStreamReader; public class HttpPostJson { public static void main(String[] args) throws Exception { String url = "http://example.com/api"; String json = "{\"username\":\"test\",\"password\":\"123456\"}"; HttpClient httpClient = HttpClientBuilder.create().build(); HttpPost request = new HttpPost(url); // 设置请求头 request.setHeader("Content-Type", "application/json"); // 设置请求参数 StringEntity params = new StringEntity(json); request.setEntity(params); // 发送POST请求 HttpResponse response = httpClient.execute(request); // 获取返回结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } // 打印返回结果 System.out.println(result.toString()); } } ``` 以上示例代码仅供参考,实际使用时需要根据自己的需求进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值