2

我正在使用 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'}

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

4

1 回答 1

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

希望能帮助到你。

于 2013-02-19T00:40:10.393 回答