HttpURLConnection出现cannot write request body after response has been read

HttpURLConnection 中出现java.net.ProtocolException: cannot write request body after response has been read

HttpURLConnection是Android原生自带的网库请求框架,因为轻量级的原因很多SDK会使用到它,最近在项目中频繁出现java.net.ProtocolException: cannot write request body after response has been read,通过排查是某个SDK中使用到了HttpURLConnection导致的,代码如下:

       private static void b(String urlStr, boolean isPost, boolean jsonTyp, String params, Network network) {
        DataOutputStream dataOutputStream = null;
        HttpURLConnection httpURLConnection = null;
        boolean requestSuccess = false;


        label:
        {
            try {
                requestSuccess = true;
                URL url = new URL(urlStr);
                if (network != null && Build.VERSION.SDK_INT >= 21) {
                    httpURLConnection = (HttpURLConnection) network.openConnection(url);
                } else {
                    httpURLConnection = (HttpURLConnection) url.openConnection();
                }

                httpURLConnection.setConnectTimeout(10000);
                httpURLConnection.setReadTimeout(10000);
                httpURLConnection.setDoInput(true);
                if (isPost) {
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                } else {
                    httpURLConnection.setRequestMethod("GET");
                    httpURLConnection.setDoOutput(false);
                }

                httpURLConnection.setUseCaches(false);
                httpURLConnection.setInstanceFollowRedirects(true);
                if (jsonTyp) {
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                } else {
                    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                httpURLConnection.setRequestProperty("connection", "Keep-Alive");
				//1 httpURLConnection.connect(); 引起异常的代码
				 httpURLConnection.connect();

                if (params != null) {
                //2  httpURLConnection.getOutputStream()
                    dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
                    byte[] paramsBytes = params.getBytes("UTF-8");
                    dataOutputStream.write(paramsBytes, 0, paramsBytes.length);
                    dataOutputStream.flush();
                    dataOutputStream.close();
                } 


                if (httpURLConnection.getResponseCode() != 200) {
                    if (httpURLConnection.getResponseCode() == 302) {
                        String locationUrl;
                        if ((locationUrl = httpURLConnection.getHeaderField("Location")) != null && !locationUrl.isEmpty()) {
                            b(locationUrl, isPost, jsonTyp, params, network);
                            requestSuccess = false;
                        } else {
                            requestSuccess = false;
                        }
                    } else {

                        requestSuccess = false;
                    }
                } else {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    StringBuffer stringBuffer = new StringBuffer();

                    String tempStr;
                    while ((tempStr = bufferedReader.readLine()) != null) {
                        tempStr = new String(tempStr.getBytes("UTF-8"));
                        stringBuffer.append(tempStr);
                    }

                    bufferedReader.close();

                    requestSuccess = false;
                }
                break label;
            } catch (Exception e) {
                e.printStackTrace();

                requestSuccess = false;

            } finally {
                if (requestSuccess) {
                    if (httpURLConnection != null) {
                        httpURLConnection.disconnect();
                    }

                    if (dataOutputStream != null) {
                        try {
                            dataOutputStream.close();
                        } catch (IOException ioe) {
                            ioe.printStackTrace();
                        }
                    }

                }
            }

            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }

            if (dataOutputStream != null) {
                try {
                    dataOutputStream.close();
                    return;
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
            }

            return;
        }

        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }

        if (dataOutputStream != null) {
            try {
                dataOutputStream.close();
            } catch (IOException var23) {
                var23.printStackTrace();
            }
        }
    }


在HttpURLConnection系统底层使用的Okhttp,getOutputStream()在com.squareup.okhttp.internal.hucHttp.URLConnectionImpl源码:

        @Override public final OutputStream getOutputStream() throws IOException {
    connect();
    BufferedSink sink = httpEngine.getBufferedRequestBody();
    if (sink == null) {
      throw new ProtocolException("method does not support a request body: " + method);
    } else if (httpEngine.hasResponse()) {
      throw new ProtocolException("cannot write request body after response has been read");
    }
    return sink.outputStream();
  }


显而易见,当httpEngine.hasResponse() 不等于null时候就会触发这个异常

解决办法就是使用到getOutputStream()的时候前面就不要调用connect()了,因为getOutputStream内部会检查调用connect()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用 `HttpURLConnection` 获取 API 的响应,可以按照以下步骤进行操作: 1. 创建 `URL` 对象,指定要请求的 API 的 URL: ```java URL url = new URL("https://api.example.com/endpoint"); ``` 2. 打开连接并设置请求方法为 GET(或其他适当的方法): ```java HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); ``` 3. 如果需要设置请求头,可以使用 `setRequestProperty` 方法添加请求头参数: ```java connection.setRequestProperty("Content-Type", "application/json"); ``` 4. 发送请求,并获取响应状态码: ```java int responseCode = connection.getResponseCode(); ``` 5. 根据响应状态码判断请求是否成功: ```java if (responseCode == HttpURLConnection.HTTP_OK) { // 请求成功,读取响应内容 InputStream inputStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应内容 System.out.println(response.toString()); } else { // 请求失败,根据需要处理错误 System.out.println("请求失败,错误码:" + responseCode); } ``` 6. 最后,记得关闭连接: ```java connection.disconnect(); ``` 以上是使用 `HttpURLConnection` 获取 API 响应的基本步骤。你可以根据需要调整和扩展代码来适应不同的场景和要求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值