Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

docker

I want to using docker remote api in this. I have succeed in this command to create 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 to create 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 throw error:

invalid character 'I' looking for beginning of value

I just add header information and add param pair about "Image:test_remote_reg".
What is wrong about my java code? What difference is between they? What should I edit for my java code?

like image 243
v11 Avatar asked Feb 10 '26 06:02

v11


1 Answers

Considering this is a json call, you could use one of the answers of HTTP POST using JSON in Java, like (replace the JSON part by 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();
}
like image 131
VonC Avatar answered Feb 13 '26 16:02

VonC



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!