我一直陷入困境 - 当运行httpsurlconnection调用时,我试图设置一系列标题但是在调试它时显示我添加的标题为NULL。
代码:
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(proxy);
//HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setDoInput(true);
con.setDoOutput(true);
//add reuqest header
con.setRequestMethod("POST");
con.addRequestProperty("Accept-Language", "en-GB");
con.addRequestProperty("X-ApiKey", "xxxx-xxx-xxx-xxx-xxx");
con.addRequestProperty("Content-Type", "application/json");
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Password", "xxxxxxxxxxxxxx"));
postParameters.add(new BasicNameValuePair("Email", "xxxxx.xxxxx@xxxxxxx.xxxx"));
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os));
writer.write(getQuery(postParameters));
writer.flush();
writer.close();
os.close();
为了测试它们是否正确设置我添加了
con.getHeaderField("X-ApiKey");
con.getHeaderFields();
确定我的标题字段是否已正确设置。然而,似乎他们没有。
相应的回应:
Post Headers: null
Post Headers: {Content-Length=[11339], Connection=[keep-alive], X-Frame-Options= [SAMEORIGIN], X-Request-Identifier=[xxxxxxxxxxxxxxxxxx], Date=[Wed, 05 Oct 2016 16:56:49 GMT], Content-Type=[text/html], null=[HTTP/1.1 400 Bad Request], Cache-Control=[private]}
我在上面的代码中出错了哪个没有正确设置标题。
答案 0 :(得分:2)
您应该使用con.getRequestProperty("X-ApiKey")
和con.getRequestProperties()
方法getHeaderField("")
会从响应标头返回标头字段的值。这非常令人困惑,因此应该更好地称为getResponseHeaderField("name")
输出不为空,因为在openConnection(URL)
被调用后,您的连接已经来自服务器的响应。