我正在使用Java。我如何制作一个HTTP POST调用API并在body中仅通知“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'}
如果这是正确的,有人可以给我一个例子吗?
答案 0 :(得分: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();
}
}
希望它有所帮助。