Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Java从REST服务读取数据_C#_Java_Http_Http Authentication - Fatal编程技术网

C# 使用Java从REST服务读取数据

C# 使用Java从REST服务读取数据,c#,java,http,http-authentication,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 use

我正在试图弄清楚如何从需要身份验证且运气不佳的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.
我做错了什么


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

Java使用UTF-8编码,getBytes()返回与本地主机编码(可能是或不是ASCII)对应的字节。这会给你更多的细节


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

答案来自注释中的Codo-Basic而不是Basic。

什么是“不工作”?您是否尝试过使用Wireshark查看这两种方法在网络上的区别?哦,对不起。添加了上面的结果。您对服务器是否正确实现RFC 2617有多大把握?例如,它是否知道身份验证方案令牌不区分大小写?请写“Basic”而不是“Basic”,然后重试。