获取HttpUrlConnection post请求的请求数据

是否可以获取HttpUrlConnection post请求的请求数据

响应头有contentLength,能拿到响应大小

可以的,示例代码如下:


 private void doHttpRequest() {
        try {
            URL url = new URL("http://192.168.xxx.xxx:8080/xxx");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection","keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.connect();
            String json = getJsonContent();
            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            int responseCode = conn.getResponseCode();
            android.util.Log.e("tag", "responseCode = " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream input = conn.getInputStream();
                StringBuilder sb = new StringBuilder();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb.append((char) ss);
                }
                android.util.Log.e("tag", "请求结果 = " + sb.toString());
                input.close();
            }
            conn.disconnect();
        } catch (Exception e) {
            android.util.Log.e("tag", "出现异常: " + e.toString());
            e.printStackTrace();
        }
    }

是的,可以通过调用HttpUrlConnection的getOutputStream()方法来获取输出流,然后将请求数据写入输出流中。例如:

OutputStream os = connection.getOutputStream();
os.write(requestData.getBytes());
os.flush();
os.close();

还需要在调用getOutputStream()之前设置HttpUrlConnection的请求方法为POST,并设置Content-Type请求头,以便服务器端正确处理请求数据。例如:

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