Jsoup HTTP POST with payload

亡梦爱人 提交于 2019-12-14 01:13:53

问题


I am trying to make this http request via Jsoup: http://api.decarta.com/v1/[KEY]/batch?requestType=geocode as given here. And here is my code for the same:

                String postUrl=postURLPrefix+apiKey+"/batch?requestType=geocode";
                System.out.println(postUrl);
                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();

The jsonPayload.toString() gives this:

{"payload":["146 Adkins Street,Pretoria,Pretoria,Gauteng","484 Hilda Street,Pretoria,Pretoria,Gauteng","268 Von Willich Street,Centurion,Centurion,Gauteng","100 Lion Road,Pretoria,Pretoria,Gauteng","Poligoon Street,Pretoria,Pretoria,Gauteng","91 Hornbill Street,Pretoria,Pretoria,Gauteng","55 Eland Street,Pretoria,Pretoria,Gauteng","31 Pelican Avenue,Centurion,Centurion,Gauteng","308 The Hillside Street,Pretoria,Pretoria,Gauteng","8 Spekhout Avenue,Centurion,Centurion,Gauteng","108 Apiesdoring Street,Pretoria,Pretoria,Gauteng","521 Louis Trichardt Street,Pretoria,Pretoria,Gauteng","31 Leopard Road,Pretoria,Pretoria,Gauteng","648 Klippan Street,Pretoria,Pretoria,Gauteng","13 Sweetpea Avenue,Pretoria,Pretoria,Gauteng","232 Kemphaan Street,Centurion,Centurion,Gauteng","32 Cantonments Road,Centurion,Centurion,Gauteng","882 Burlington St,Roseville,Gauteng","15 Brits Street,Olympus Ridge Complex,Centurion,Gauteng","15 Brits Street,Monument Park,Centurion,Gauteng","35 De La Rey Road,Monument Park,Centurion,Gauteng","112 Diamond St,Monument Park,Klerksoord,Gauteng","Hendrik Verwoerd Drive,Lyttelton,Centurion,Gauteng","777 Gambry Avenue,Garsfontein,Pretoria,Gauteng","57 Pheasant Avenue,Waterkloof Rand Corporatepark,Akasia,Gauteng","18 Huilboom Street,Manitoba Mews,Pretoria,Gauteng","75 Gousblom Avenue,Euro Stadt,Pretoria,Gauteng","88 Cambridge Avenue,Garsfontein,Centurion,Gauteng","662 Pual Kruger Street,Olympus Ridge Complex,Pretoria,Gauteng","231 Charles Street,Hatfield,Pretoria,Gauteng","9 Kobus Street,Pretoria West,Centurion,Gauteng","96 Siersteen Road,Byron Place,Pretoria,Gauteng","262 Molopo Avenue,Montana Crossing,Pretoria,Gauteng","171 Sonja Street,Moreleta Park,Centurion,Gauteng","751 Lucas Meyer Street,Moreleta Park,Pretoria,Gauteng","499 Moot Street,Centurion Lifestyle Centre,Pretoria,Gauteng","4 Hofsanger Road,Villa Lanei,Centurion,Gauteng","51 Newark Street,Centurion,Gauteng","25 Anton Street,Lyttelton,Centurion,Gauteng","15 Brits Street,Garsfontein Ext 10,Centurion,Gauteng","172 Wildeamandel Street,La Motagne,Pretoria,Gauteng","15 Fillicia Street,Waterkloof,Pretoria,Gauteng","20 Slagveld Street,Centurion,Gauteng","678 Rankdoring Street,Waterkloof Glen,Pretoria,Gauteng","7 Hillips Street,Faerie Glen X 34,Pretoria,Gauteng","59 Malherbe Street,Willows,Pretoria,Gauteng","204 Festival Street, Unit 1\",Willows,Pretoria","310 Cliff Avenue,Manitoba Mews,Pretoria,Gauteng","294 Panorama Road,Hatfield,Centurion,Gauteng","79 Buitenkant Street,Opera Plaza,Pretoria,Gauteng"]}

Which is a perfectly valid json.

However Jsoup each time returns HTTP status 400(malformed). So how do I send proper http POST with JSON payload using Jsoup if at all this is possible.(Pls note that its payload and not an ordinary key-val pair in url).


回答1:


What you need is to post raw data. That functionality has been implemented but it hasn't been added yet. Check this pull request https://github.com/jhy/jsoup/pull/318 . Do you really need to use jsoup for this? I mean you could use HttpURLConnection (this is what jsoup uses underneath) to make the request and then pass the response to jsoup as a string.

Here is an example of HttpURLConnection taken (but simplified and added json/raw data) from www.mkyong.com

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {

    public static void main(String[] args) {

        try {

            String url = "http://www.google.com";

            URL obj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setReadTimeout(5000);
            conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            conn.addRequestProperty("User-Agent", "Mozilla");
            conn.addRequestProperty("Referer", "google.com");

            conn.setDoOutput(true);

            OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            w.write("SOME_JSON_STRING_HERE");
            w.close();

            System.out.println("Request URL ... " + url);

            int status = conn.getResponseCode();

            System.out.println("Response Code ... " + status);

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String inputLine;
            StringBuffer html = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                html.append(inputLine);
            }

            in.close();
            conn.disconnect();

            System.out.println("URL Content... \n" + html.toString());
            System.out.println("Done");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}



回答2:


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


来源:https://stackoverflow.com/questions/27463036/jsoup-http-post-with-payload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!