简体   繁体   中英

RESTful java Client and HttpClient

I have a Curl command which I use to execute in UNIX.

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

I was trying to do this using Java.

I tried using Restlet and also HttpClient, but none works. 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?

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.

Then instead of dealing directly with the status code and entity, you could turn over the fluent API as in

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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