c#-使用Java读取REST服务
作者:互联网
我试图弄清楚如何从需要身份验证且没有运气的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.
我怎么了?
谢谢-戴夫
解决方法:
在用户名/密码的编码中:
Java使用UTF-8编码,而getBytes()返回与本地主机编码相对应的字节(可能是ASCII或不是ASCII). javadoc of String为您提供了更多细节.
在c#和Java中同时打印此类编码字符串的值,并检查它们是否匹配.
标签:http,java,c,http-authentication 来源: https://codeday.me/bug/20191208/2088543.html