开发者

Use Java to read from a REST service

I am trying to figure out how to read from a REST source that requires authentication and having no luck. I have this working fine using C# as follows:

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();

But for Java the follow开发者_如何学Pythoning is not working:

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();

The stream is returning:

Error downloading template

Packet: test_packet
Template: NorthwindXml

Error reading authentication header.

What am I getting wrong?

thanks - dave


In your encoding of username/password:

Java uses UTF-8 encoding, and getBytes() returns the bytes corresponding to the local host encoding (who may be or not ASCII). The javadoc of String gives you more detail.

Print the values of such encoded Strings both in c# and Java and check if they match.


The answer came from Codo in a comment - Basic instead of BASIC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜