2013-02-18 68 views
2

我正在使用Java。我如何创建一个HTTP POST调用API并仅在主体中通知“JSON”值(不带参数名称)?通过HTTP POST方法调用API而不使用参数名称的正文

每例如调用这个URL:https://api.nimble.com/api/v1/contact?access_token=12123486db0552de35ec6daa0cc836b0(POST方法),并在身体只会有这个(不带参数名):

{'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'} 

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

回答

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

希望它能帮助。

+0

非常感谢您的回复,但它不工作,我调整了代码并将json值放入json var字符串中,但在启动执行之前发生错误: 'code' java.util.concurrent .ExecutionException:org.apache.catalina.LifecycleException:无法启动组件[StandardEngine [Catalina] .StandardHost [localhost] .StandardContext [/ nimble]] 我试着用这段代码[链接](http:// stackoverflow .com/questions/15276056/409-http-error-when-trying-to-send-a-json-string-in-post-request),但是我得到409 http错误:(。再次感谢你! – 2013-03-07 16:24:24

+0

你好吗确定你的json是有效的? – Bdloul 2013-03-11 23:59:09

+0

json不正确,我认为“http://jsonviewer.stack.hu/”正确验证,但不是,“http://jsonlint.org/”正确验证。汉克斯。 – 2013-03-28 20:25:29

相关问题