gpt4 book ai didi

java - DataOutputStream 和 OutputStreamWriter 的区别 : String compatibility?

转载 作者:行者123 更新时间:2023-12-02 11:18:55 24 4
gpt4 key购买 nike

我对 Java 很陌生,但是当使用 OutputStreamWriter 和 DataOutputStream 以及 HttpUrlConnection 的 POST 请求时,我得到了不同的结果。

使用 DataOutputStream 时可以附加参数。

URL url = new URL("https://www.google-analytics.com/debug/collect");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

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

String parameters = "v=1&tid=UA-62749954-12&cid=test.clientid.456&t=event&ec=offline_cv&ea=register";

DataOutputStream writer = new DataOutputStream(conn.getOutputStream());
writer.writeBytes(parameters);

writer.close();
conn.connect();

回应:

{  "hitParsingResult": [ {    "valid": true,    "parserMessage": [ ],    "hit": "/debug/collect?v=1\u0026tid=UA-62749954-12\u0026cid=test.clientid.456\u0026t=event\u0026ec=offline_cv\u0026ea=register"  } ],  "parserMessage": [ {    "messageType": "INFO",    "description": "Found 1 hit in the request."  } ]}

但是,使用 OutputStreamWriter 时我无法附加参数。

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(URLEncoder.encode(parameters, "UTF-8"));

回应:

{  "hitParsingResult": [ {    "valid": false,    "parserMessage": [ {      "messageType": "ERROR",      "description": "A value is required for parameter 'v'. Please see https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#v for details.",      "messageCode": "VALUE_REQUIRED",      "parameter": "v"    } ],    "hit": "/debug/collect"  } ],  "parserMessage": [ {    "messageType": "INFO",    "description": "Found 1 hit in the request."  } ]}

是不是因为DataOutputStream兼容String,而OutputStreamWriter不兼容?

最佳答案

1)问题出在这里:

URLEncoder.encode(parameters, "UTF-8")

您的参数已进行 url 编码。调用此方法会使它们格式错误。

2)使用一些工具来监控HTTP请求,了解请求和响应发生了什么。

关于java - DataOutputStream 和 OutputStreamWriter 的区别 : String compatibility?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50072691/

24 4 0
文章推荐: java - 使用泛型 : Instantiating an object of a generic class with parent and child values in generic
文章推荐: ruby-on-rails-4 - Capistrano 部署 :assets:restore_manifest Rails assets manifest file (or backup file) not found
文章推荐: python - 类型错误 : ufunc 'true_divide' output (typecode 'd' ) could not be coerced to provided output parameter (typecode 'q' )
文章推荐: java - 如何在java中服务器端获取