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?

v11
  • 1,684
  • 4
  • 24
  • 47

1 Answers1

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();
}
Community
  • 1
  • 1
VonC
  • 1,042,979
  • 435
  • 3,649
  • 4,283
  • You have other options at http://stackoverflow.com/a/27057519/6309. In your case, the `StringEntity` would be `StringEntity("{\"Image\":" + imageName + "}")` – VonC Jul 14 '15 at 08:06
  • 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! – v11 Jul 14 '15 at 08:29