使用Java从REST服务中读取

时间:2011-08-15 23:55:30

标签: c# java http http-authentication

我试图弄清楚如何从需要身份验证且没有运气的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.

我出错了什么?

谢谢 - 戴夫

2 个答案:

答案 0 :(得分:2)

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

Java使用UTF-8编码,getBytes()返回与本地主机编码对应的字节(可能是ASCII也可能不是ASCII)。 javadoc of String为您提供了更多详细信息。

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

答案 1 :(得分:1)

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