Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make this REST get method in Java?

I have the following REST get Request that works successfully:

enter image description here

The result is a XML document that I then want to parse. I tried the same in Java:

I use the following code:

public void getRootService() throws ClientProtocolException, IOException {

    HttpGet httpGet = new HttpGet("https://localhost:9443/ccm/rootservices");
    httpGet.setHeader("Accept", "text/xml");
    HttpResponse response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream in = entity.getContent();
    String projectURL = XMLDocumentParser.parseDocument(in);

    System.out.println(projectURL);
    HttpGet getProjectsRequest = new HttpGet("https://localhost:9443/ccm/process/project-areas");
    getProjectsRequest.setHeader("Content-Type", "application/xml;charset=UTF-8");
    getProjectsRequest.setHeader("Accept-Charset", "UTF-8");
    getProjectsRequest.setHeader("Accept", "application/xml");


    ResponseHandler<String> handler = new BasicResponseHandler();
    String projectResponse = client.execute(getProjectsRequest, handler);
    //String projectResponse = client.execute(getProjectsRequest, handler);

    System.out.println(projectResponse);

}

But how can I do the authentication? I tried to just add another header field for the value "Authorization" but then I don't get the same result.


1 Answers

I think you have to create a UsernamePasswordCredentials, something along the lines of (untested);

CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
    new AuthScope("somehost", AuthScope.ANY_PORT), 
    new UsernamePasswordCredentials("username", "password"));

HttpClient httpclient = new DefaultHttpClient();
httpclient.setCredentialsProvider(credsProvider);

See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html

Edit:
Just tried the following code and successfully called a REST service on our dev environment that is BASIC protected.

public static void main(String[] args) throws ClientProtocolException, IOException {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(
        new AuthScope("dev.*******.com", AuthScope.ANY_PORT), 
        new UsernamePasswordCredentials("*****", "******"));


    DefaultHttpClient client = new DefaultHttpClient();
    client.setCredentialsProvider(credsProvider);

    String url = "http://dev.******.com:18081/path/to/service/id.xml";

    HttpGet get = new HttpGet(url);
    ResponseHandler<String> handler = new BasicResponseHandler();
    String resp = client.execute(get, handler);

    System.out.println(resp);
  }
like image 87
Qwerky Avatar answered Jun 22 '26 05:06

Qwerky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!