简体   繁体   English

RESTful Java客户端和HttpClient

[英]RESTful java Client and HttpClient

I have a Curl command which I use to execute in UNIX. 我有一个用于在UNIX中执行的Curl命令。

curl --digest -u 'user':'pass' 'https://<URL>/getCustomers' (which is working for me)

I was trying to do this using Java. 我试图使用Java做到这一点。

I tried using Restlet and also HttpClient, but none works. 我尝试使用Restlet以及HttpClient,但均无效果。 I don't know the exact way to implement that. 我不知道确切的实现方法。

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();
  }
}

I don't know where I did the mistake, can you guys help me out? 我不知道我在哪里弄错了,你们能帮我吗? The output is a JSON, can you guys let me know how to catch the output, too? 输出是JSON,你们也可以让我知道如何捕获输出吗?

Your question misses a few details such as what is the error you get. 您的问题缺少一些细节,例如您遇到的错误是什么。

I would suggest to read the HTTPClient documentation and more specifically the section about authentication and how preemptive works. 我建议阅读HTTPClient文档,尤其是有关身份验证和抢占方式的部分。

Then instead of dealing directly with the status code and entity, you could turn over the fluent API as in 然后,您可以直接使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM