使用Java从REST服务中读取

本文关键字:读取 服务 REST Java 使用 | 更新日期: 2023-09-27 18:05:35

我正试图弄清楚如何从需要身份验证且没有运气的REST源中读取。我使用c#可以正常工作,如下所示:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create(filename);
request.Accept = "application/xml";
request.ContentType = "application/xml";
request.KeepAlive = true;
// this part is not used until after a request is refused, but we add it anyways
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(filename), "Basic", new NetworkCredential(username, password));
request.Credentials = myCache;
// this is how we put the uname/pw in the first request
string cre = String.Format("{0}:{1}", username, password);
byte[] bytes = Encoding.ASCII.GetBytes(cre);
string base64 = Convert.ToBase64String(bytes);
request.Headers.Add("Authorization", "Basic " + base64);
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
return response.GetResponseStream();

但是对于Java来说,下面的代码不能工作:

URL url = new URL(dsInfo.getFilename());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
conn.setRequestProperty("Content-Type", "application/xml");
BASE64Encoder encoder = new BASE64Encoder();
String encodedCredential = encoder.encode( (dsInfo.getUsername() + ":" + dsInfo.getPassword()).getBytes() );
conn.setRequestProperty("Authorization", "BASIC " + encodedCredential);
conn.connect();
InputStream responseBodyStream = conn.getInputStream();

流返回:

Error downloading template
Packet: test_packet
Template: NorthwindXml
Error reading authentication header.

我错在哪里?

thanks - dave

使用Java从REST服务中读取

在您的用户名/密码编码中:

Java使用UTF-8编码,getBytes()返回与本地主机编码(可能是也可能不是ASCII)相对应的字节。String的javadoc给出了更多的细节。

在c#和Java中打印这些编码字符串的值,并检查它们是否匹配。

答案来自Codo的评论- Basic而不是Basic。