简体   繁体   English

在JAVA中将JSON对象作为POST发送到Rest服务

[英]Sending a JSON object to a rest service as a POST in JAVA

Hi I am sort of new to Java and making POST request to urls. 嗨,我是Java的新手,正在向URL发出POST请求。 However I am trying to send a post request to a url that expects the body to look like this: 但是,我试图将发布请求发送到希望正文看起来像这样的网址:

{ "startTime":"2013/09/09 11:00",
  "endTime":"2013/09/09 13:00",
  "pool": "webscr,paymentserv",
  "regexs":["string1","string2"],
  "searchMode":"simple",
}

To me this looks like a JSON object. 对我来说,这看起来像一个JSON对象。 So In my code I am trying to do the following 所以在我的代码中,我尝试执行以下操作

    String url = "http://restAPIService.com/regex/request";

    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost(url);

    List<BasicNameValuePair> urlParameters = new ArrayList<BasicNameValuePair>();
    urlParameters.add(new BasicNameValuePair("startTime", startTime));
    urlParameters.add(new BasicNameValuePair("endTime", endTime));
    urlParameters.add(new BasicNameValuePair("pool", pool));
    for (int i = 0; i < regexArray.length; i++) {
        urlParameters.add(new BasicNameValuePair("regexs[]",regexArray[i]));
   }

    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    HttpResponse response = client.execute(post);

    BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

However when I run this code I get a response of 415. I think this is because this name value pair isn't creating a JSON objects, but I have no idea how to create a Json object in Java and documentation online has not helped. 但是,当我运行此代码时,得到的响应为415。我认为这是因为该名称值对未创建JSON对象,但是我不知道如何在Java中创建Json对象,并且在线文档也无济于事。 Presumably a basic name value pair would work but not all pairs are string string. 大概可以使用一个基本名称值对,但是并非所有的名称对都是字符串。 Notice that the regexs field is an array of strings. 注意,regexs字段是一个字符串数组。

What would be the best way to create a JSON object to send as the url parameters or the request body? 创建JSON对象作为url参数或请求正文发送的最佳方法是什么?

Help! 救命! Thanks! 谢谢!

Note: I also tried following something like this HTTP POST using JSON in Java but I couldn't get it to work for specific purpose. 注意:我也尝试使用Java中的JSON遵循类似HTTP POST的方法,但是我无法使其用于特定目的。 If it helps my regexArray doesnt have to be an array (I only always have on regex so this field in the object will always be like this regexs: ["string1"] 如果有帮助,我的regexArray不必是一个数组(我只在regex上总是有,因此对象中的此字段将始终像这样的regexs:[“ string1”]

 if(request.getPostMap().size() > 0) {
    List<NameValuePair>list=new ArrayList<NameValuePair>();
    Map<String, String> postMap = request.getPostMap();
    for (String key : postMap.keySet()) {
    String value = postMap.get(key);
    value = value==null ? "" : value;
    list.add(new BasicNameValuePair(key, value));
    }
    httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
  }

this snippet code may help you, postMap is your JSON value 该代码段可能会对您有所帮助, postMap是您的JSON值

您可以在Java中使用一些JSON工具包,例如json-simplegson等。

Just make a Bean with required fields and then populate the object of it and then pass the object to gson. 只需使用必填字段制作Bean,然后填充它的对象,然后将该对象传递给gson。
For Instance: 例如:

public class MyBean {

private String startTime;
private String endTime;
private String pool;
private List<String> regexes;
private String searchMode;

// getters and setters.....
}

Now populate the object of MyBean. 现在填充MyBean的对象。 Lets say object name is myBean. 可以说对象名称是myBean。
Convert it like this:- 像这样转换它:

Gson gson = new Gson();
String json = gson.toJson(myBean);

And you are done! 您完成了!
Apart from gson you can also use jackson libraries for the same task if you want. 除了gson之外,如果需要还可以将jackson库用于同一任务。 But, to start with, I think Gson is quite simple. 但是,首先,我认为Gson非常简单。 There are also options like whether you want to serialize nulls or not, prettyprint json or not and a lot many which will help you. 还有一些选项,例如您是否要序列化null,是否要序列化prettyprint json,还有很多选项将对您有所帮助。 Its just a start, just explore Gson library. 它只是一个开始,只需探索Gson库。

I would also suggest gson. 我也建议gson。 I'm not familiar with json-simple, but would also take a look at jackson as a potential alternative. 我不熟悉json-simple,但也可以将jackson看作是一种潜在的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM