RESTful java客户端和HttpClient
我有一个Curl命令,用于在UNIX中执行RESTful java客户端和HttpClient,java,curl,restlet,Java,Curl,Restlet,我有一个Curl命令,用于在UNIX中执行 curl --digest -u 'user':'pass' 'https://<URL>/getCustomers' (which is working for me) curl--digest-u'user':'pass'https:///getCustomers"(对我有效) 我试着用Java来做这件事 我尝试使用Restlet和HttpClient,但都不起作用。我不知道具体的实现方法 private static void g
curl --digest -u 'user':'pass' 'https://<URL>/getCustomers' (which is working for me)
curl--digest-u'user':'pass'https:///getCustomers"(对我有效)
我试着用Java来做这件事
我尝试使用Restlet和HttpClient,但都不起作用。我不知道具体的实现方法
private static void get() {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet("https://<URL>/getCustomers");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(USER, PASSWORD));
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void get(){
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpGet getRequest=新的HttpGet(“https:///getCustomers");
addHeader(“接受”、“应用程序/json”);
HttpResponse response=httpClient.execute(getRequest);
httpClient.getCredentialsProvider().setCredentials(新的AuthScope(AuthScope.ANY_主机、AuthScope.ANY_端口)、新的用户名密码凭据(用户、密码));
如果(response.getStatusLine().getStatusCode()!=200){
抛出新的RuntimeException(“失败:HTTP错误代码:”+response.getStatusLine().getStatusCode());
}
BufferedReader br=新的BufferedReader(新的InputStreamReader((response.getEntity().getContent()));
字符串输出;
System.out.println(“从服务器输出…”\n);
而((output=br.readLine())!=null){
系统输出打印项次(输出);
}
httpClient.getConnectionManager().shutdown();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
我不知道我哪里出的错,你们能帮我吗?
输出是JSON,你们能告诉我如何捕获输出吗 你的问题遗漏了一些细节,比如你的错误是什么 我建议阅读HTTPClient文档,更具体地说,阅读关于抢占机制及其工作原理的部分 然后,不必直接处理状态代码和实体,您可以将fluent API转换为
Executor executor = Executor.newInstance()
.auth(new HttpHost("example.com"), "username", "password")
.authPreemptive(new HttpHost("example.com"));
executor.execute(Request.Get("http://example.com/foobar.json"))
.returnContent().asString();
编译错误?例外情况?输出?在执行之前,首先需要调用setCredentials。@Fortega我已获得HTTP状态401,身份验证失败。但有了同样的证书,我可以使用curl从命令运行。