3

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?

1 Answer 1

4

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();
}
Sign up to request clarification or add additional context in comments.

2 Comments

You have other options at stackoverflow.com/a/27057519/6309. In your case, the StringEntity would be StringEntity("{\"Image\":" + imageName + "}")
Wow, so cool for your answer. I have understood what is wrong about my code. It is json parameters, But I just use NameValuePair. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.