我正在使用HTTPClient
发出网络请求。在linux部分中,使用以下命令将状态返回为OK
。 java中的相同内容是返回未经授权的状态代码401
。
来自linux的命令:
curl -X GET -ik -H 'Accept: application/json' --user test:test http://api.uat.testapi.com
要访问它,我使用的java代码如下:
HttpHost targetHost = new HttpHost("http://api.uat.testapi.com/");
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()),
new UsernamePasswordCredentials("test","test"));
HttpGet httppost = new HttpGet("http://api.uat.testapi.com/");
httppost.addHeader("Accept","application/json");
HttpResponse response = httpclient.execute(httppost);
System.out.println("status>>>>"+response.getStatusLine());
我的回复为:HTTP/1.1 401 Unauthorized
。
任何解决这个问题的指针都会有所帮助
提前致谢。
答案 0 :(得分:0)
我认为你需要设置HttpState来使用身份验证。使用
httpClient.getParams().setAuthenticationPreemptive(true);
做同样的事。
答案 1 :(得分:0)
看起来你正在用curl和一个带HttpClient的POST请求发出GET请求;我怀疑服务器没有接受POST请求。
您是否需要使用HttpGet:
HttpGet method = new HttpGet("http://api.uat.testapi.com");
...
HttpResponse response = httpclient.execute(method);
希望有帮助...
答案 2 :(得分:0)
try below code :
HttpURLConnection connection = (HttpURLConnection) new URL("url").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization", "Basic "+
new sun.misc.BASE64Encoder().encode( "username:password".getBytes() ));
System.out.println("status>>>>"+connection.getResponseCode());
答案 3 :(得分:0)
尝试使用以下代码....根据您的设置exe url等进行更改
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials("username", "password"));
HttpGet httpget = new HttpGet("YOURURL");
System.out.println("executing request" + httpget.getRequestLine());
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
catch(Exception e)
{
e.printStackTrace();
}
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}