【问题标题】:How to use docker remote api to create container In java?如何使用 docker remote api 在 java 中创建容器?
【发布时间】:2015-10-02 17:52:05
【问题描述】:

我想在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 代码编辑什么?

【问题讨论】:

    标签: java docker


    【解决方案1】:

    考虑到这是一个 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();
    }
    

    【讨论】:

    • 您在stackoverflow.com/a/27057519/6309 有其他选择。在您的情况下,StringEntity 将是 StringEntity("{\"Image\":" + imageName + "}")
    • 哇,你的回答太酷了。我已经了解我的代码有什么问题。它是 json 参数,但我只使用 NameValuePair。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多