【问题标题】:API call by HTTP POST method without using parameter name for the body通过 HTTP POST 方法调用 API,不使用正文的参数名称
【发布时间】:2013-02-03 12:33:16
【问题描述】:

我正在使用 Java。如何进行 HTTP POST 调用 API 并仅在正文中通知“JSON”值(不带参数名称)?

例如调用这个 URL:https://api.nimble.com/api/v1/contact?access_token=12123486db0552de35ec6daa0cc836b0(POST METHOD)并且在正文中只有这个(没有参数名称):

{'fields':{'first name': [{'value': 'Jack','modifier': '',}],'last name': [{'value': 'Daniels','modifier': '',}],'phone': [{'modifier': 'work','value': '123123123',}, {'modifier':'work','value': '2222',}],},'type': 'person','tags': 'our customers\,best'}

如果这是正确的,有人可以给我一个例子吗?

【问题讨论】:

    标签: java api http post nimble


    【解决方案1】:

    将此库用于网络部分:http://hc.apache.org/

    将此库用于 json 部分:http://code.google.com/p/google-gson/

    例子:

    public String examplePost(DataObject data) {
            HttpClient httpClient = new DefaultHttpClient();
    
            try {
                HttpPost httppost = new HttpPost("your url");
                // serialization of data into json
                Gson gson = new GsonBuilder().serializeNulls().create();
                String json = gson.toJson(data);
                httppost.addHeader("content-type", "application/json");
    
                // creating the entity to send
                ByteArrayEntity toSend = new ByteArrayEntity(json.getBytes());
                httppost.setEntity(toSend);
    
                HttpResponse response = httpClient.execute(httppost);
                String status = "" + response.getStatusLine();
                System.out.println(status);
                HttpEntity entity = response.getEntity();
    
                InputStream input = entity.getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(input, writer, "UTF8");
                String content = writer.toString();
                // do something useful with the content
                System.out.println(content);
                writer.close();
                EntityUtils.consume(entity);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            } finally {
                httpClient.getConnectionManager().shutdown();
            }
        }
    

    希望对你有帮助。

    【讨论】:

    • 非常感谢您的回复,但是不行,我已经修改了代码,把json值放到了json var字符串中,但是在启动执行前出现错误:codejava. util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: 无法启动组件 [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/nimble]] 我正在尝试使用此代码link,但我得到 409 http错误:(。再次感谢!
    • 你确定你的json有效吗?
    • json 不正确,我认为“jsonviewer.stack.hu”验证正确,但“jsonlint.org”验证正确。谢谢。
    猜你喜欢
    • 2019-03-31
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多