Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup HTTP POST with payload

I am trying to make this HTTP request via jsoup as given here:

http://api.decarta.com/v1/[KEY]/batch?requestType=geocode

And here is my code for that:

String postUrl = postURLPrefix + apiKey + "/batch?requestType=geocode";
String response = Jsoup.connect(postUrl).timeout(60000).ignoreContentType(true)
        .header("Content-Type", "application/json;charset=UTF-8")
        .method(Connection.Method.POST)
        .data("payload", jsonPayload.toString())
        .execute()
        .body();

jsonPayload.toString() gives this:

{
  "payload": [
    "146 Adkins Street,Pretoria,Pretoria,Gauteng",
    "484 Hilda Street,Pretoria,Pretoria,Gauteng",
    "268 Von Willich Street,Centurion,Centurion,Gauteng",
    ...
  ]
}

Which is a perfectly valid JSON.

However, jsoup each time returns HTTP status code 400 (malformed).
So, how do I send proper HTTP POST with JSON payload using jsoup if this is possible at all? (Please note that it's payload and not an ordinary key-value pair in URL)

like image 845
rahulserver Avatar asked Dec 13 '14 20:12

rahulserver


1 Answers

Use latest JSOUP library.

If you are using maven, then add below entry to pom.xml

<dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.10.2</version>
</dependency>

And below code will solves your problem.

String postUrl=postURLPrefix+apiKey+"/batch?requestType=geocode";
            System.out.println(postUrl);
            String response= Jsoup.connect(postUrl).timeout(60000).ignoreContentType(true)
                    .method(Connection.Method.POST)
                    .requestBody("payload",jsonPayload.toString())
                    .execute()
                    .body();
like image 133
Santosh Hegde Avatar answered Sep 28 '22 04:09

Santosh Hegde