我对Java很新,但是当使用带有HttpUrlConnection的POST请求的OutputStreamWriter和DataOutputStream时,我有不同的结果。
我可以在使用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不兼容吗?
答案 0 :(得分:1)
1)问题在于:
URLEncoder.encode(parameters, "UTF-8")
您的参数已经过网址编码。调用此方法会使它们格式不正确。
2)使用一些工具来监控HTTP请求,以了解请求和响应会发生什么。