首页  >  文章  >  Java  >  如何确保在 HttpURLConnection 请求中收到标头?

如何确保在 HttpURLConnection 请求中收到标头?

Susan Sarandon
Susan Sarandon原创
2024-11-16 21:05:03109浏览

How to Ensure Headers Are Received in HttpURLConnection Requests?

对 HttpURLConnection 中的标头添加进行故障排除

尝试将标头附加到 HttpURLConnection 请求时,setRequestProperty() 方法可能并不总是按预期运行,导致服务器收不到预期的内容

一个潜在的解决方案,已被证明在 TomCat 环境中有效,是利用以下代码片段:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
// Adjust these properties based on request type (POST/GET) and other requirements
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

此代码是专门为 POST 请求设计的,但您可以轻松地如有必要,请将其修改为 GET 或其他请求类型。通过应用这些更新,您应该能够成功地将标头添加到 HttpURLConnection 请求中,并确保服务器收到预期的标头。

以上是如何确保在 HttpURLConnection 请求中收到标头?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn