How to use docker remote api to create container in java?

I want to use docker remote api in this . I managed to create this command to create a container:

curl -v -X POST -H "Content-Type: application/json" -d '{"Image": " registry:2",}' http://192.168.59.103:2375/containers/create?name=test_remote_reg

      

Then I use HttpClient (4.3.1) in java to try and create a container via this code:

    String containerName = "test_remote_reg";
    String imageName = "registry:2";
    String url = DockerConfig.getValue("baseURL")+"/containers/create?name="+containerName;
    List<NameValuePair> ls = new ArrayList<NameValuePair>();
    ls.add(new BasicNameValuePair("Image",imageName));
    UrlEncodedFormEntity fromEntity = new UrlEncodedFormEntity(ls, "uTF-8");
    HttpPost post = new HttpPost(url);
    post.setHeader("Content-Type", " application/json");
    if(null!=fromEntity) post.setEntity(fromEntity);
    HttpClient client = new DefaultHttpClient();
    client.execute(post);

      

It didn't work and threw an error:

invalid character 'I' looking for beginning of value

      

I just add the header information and add a param pair about "Image: test_remote_reg".
What's wrong with my Java code? What's the difference between them? What should I change for my java code?

+3


source to share


1 answer


Considering this is a json call, you can use one of the HTTP POST responses using JSON in Java , for example (replace the JSON part with your JSON parameters)



HttpClient httpClient = new DefaultHttpClient();

try {
    HttpPost request = new HttpPost("http://yoururl");
    StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
    request.addHeader("content-type", "application/json");
    request.addHeader("Accept","application/json");
    request.setEntity(params);
    HttpResponse response = httpClient.execute(request);

    // handle response here...
}catch (Exception ex) {
    // handle exception here
} finally {
    httpClient.getConnectionManager().shutdown();
}

      

+4


source







All Articles