我希望发出HTTP POST请求并使用生成的auth_token,但while循环中的print语句只打印x-dnb-user=myusername&x-dnb-pwd=mypass
,而不是打印从服务器收到的响应。我无法弄清楚我哪里出错了。任何帮助,将不胜感激。此外,响应是作为字典给出的,并且令牌存在于字典的“授权”键中,在这种情况下如何检索令牌?
public void sampleAuth(){
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("https://maxcvservices.dnb.com/rest/Authentication");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("x-dnb-user","myemail"));
nameValuePairs.add(new BasicNameValuePair("x-dnb-pwd","mypass"));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(post);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
提前致谢!
答案 0 :(得分:0)
我认为你可能错过了Content-type
post.setHeader("Content-type", "application/x-www-form-urlencoded");
此外,在启动rd.readLine响应之前,您应该检查响应的状态代码。服务器可能已经拒绝了您,并且没有要阅读的行!
int code = response.getStatusLine().getStatusCode();
if ( code == HttpStatus.SC_OK ) {
// Now go fishing for the auth_token
// Usually these things are returned as headers
} else {
System.out.println( "You've been rejected, pal" );
}
我需要更多关于你期望的auth_token的细节,但我的猜测是它在一个名为“auth_key”的标题中,或者你可以查找它。