如何使用docker remote api创建容器在java?

时间:2015-07-14 07:49:38

标签: java docker

我想在this中使用docker remote api。 我在这个命令中成功创建了容器:

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

然后,我在java中使用HttpClient(4.3.1)尝试通过以下代码创建容器:

    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);

它不起作用,并抛出错误:

invalid character 'I' looking for beginning of value

我只是添加标题信息并添加关于“Image:test_remote_reg”的参数对 我的java代码有什么问题?他们之间有什么区别?我应该为我的java代码编辑什么?

1 个答案:

答案 0 :(得分:4)

考虑到这是一个json调用,你可以使用HTTP POST using JSON in Java的答案之一,(用你的JSON参数替换JSON部分):

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();
}