简体   繁体   English

使用HttpURLConnection的HTTP上的XML-获取错误401

[英]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.

相关问题 401使用HttpURLConnection Android发生未经授权的错误? - 401 Unauthorized Error using HttpURLConnection Android? 使用HttpUrlConnection将访问令牌发送回Google API(401错误) - Sending access token back to google api (401 error) using HttpUrlConnection Android 401使用HttpURLConnection连接到REST服务时出错 - Android 401 Error connecting to REST service using HttpURLConnection HttpUrlConnection.getInputStream 上的 HTTP 响应代码 401 - HTTP Response code 401 on HttpUrlConnection.getInputStream 在HttpURLConnection中使用PATCH方法时出错 - Getting error while using PATCH method in HttpURLConnection 使用HttpURLConnection的JAVA中的POST获得HTTP响应代码400 - POST in JAVA using HttpURLConnection getting a HTTP response code 400 尝试验证连接时收到HTTP 401错误。 - Getting HTTP 401 error while trying to validate the connection.I am using rest assured to automate 当我将使用java HttpUrlConnection类获取HTTP 504错误时 - When I will get HTTP 504 error using java HttpUrlConnection Class 使用HttpUrlConnection发送数据 - Sending data over using HttpUrlConnection 使用Android HttpURLConnection 获取Http - Http Get using Android HttpURLConnection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM