简体   繁体   中英

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. 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. 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. 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.

What would be the best way to create a JSON object to send as the url parameters or the request body?

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. 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"]

 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

您可以在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.
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. Lets say object name is 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. But, to start with, I think Gson is quite simple. 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. Its just a start, just explore Gson library.

I would also suggest gson. I'm not familiar with json-simple, but would also take a look at jackson as a potential alternative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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