[英]XML over http using HttpURLConnection - getting error 401
I am trying to send XML over http url using HttpURLConnection. 我正在尝试使用HttpURLConnection通过http url发送XML。
Following is the test curl command that I am using to test the service. 以下是我用来测试服务的test curl命令。
curl -H "Content-Type: text/xml" -H "User-Agent: some/7.88/1" -X POST --Basic -u "username:password" -d '< ?xml packet ... >' http://ip:port/some/url
curl -H“内容类型:文本/ xml” -H“用户代理:some / 7.88 / 1” -X POST-基本-u“用户名:密码” -d'<?xml数据包...>' http:// ip:port / some / url
It is working fine, but when I try to send this with following Java code: 它工作正常,但是当我尝试使用以下Java代码发送时:
Java Code: Java代码:
URL url = new URL("http://ip:port/some/url");
String requestXMLPacket = "<?xml packet ... >";
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","text/xml");
conn.setRequestProperty("User-Agent", "some/7.88/1");
conn.setRequestProperty("basic -u", "username:password");
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setUseCaches(false);
conn.setDoInput(true);
I get an error: 我收到一个错误:
java.io.IOException: Server returned HTTP response code: 401 for URL: http://ip:port/some/url
java.io.IOException:服务器返回的HTTP响应代码:401用于URL: http:// ip:port / some / url
Which means that I am not sending correct authorization. 这意味着我没有发送正确的授权。
Can you tell me what I am doing wrong here. 你能告诉我我在做什么错。
Please try adding authentication header as follows 请尝试添加身份验证标头,如下所示
String encoded = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
conn.setRequestProperty("Authorization", "Basic " + encoded);
PS. PS。 It uses Java 8 Base64 encoder
它使用Java 8 Base64编码器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.