【问题标题】:Jsoup HTTP POST with payload带有有效负载的 Jsoup HTTP POST
【发布时间】:2015-02-12 07:24:51
【问题描述】:

我正在尝试通过给定here 的 jsoup 发出这个 HTTP 请求:

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

这是我的代码:

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() 给出了这个:

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

这是一个完全有效的 JSON。

但是,jsoup 每次都返回 HTTP 状态码 400(格式错误)。
那么,如果可能的话,如何使用 jsoup 发送带有 JSON 有效负载的正确 HTTP POST? (请注意,它是payload,而不是URL中的普通键值对)

【问题讨论】:

    标签: java json kotlin http-post jsoup


    【解决方案1】:

    您需要发帖raw data。该功能已实现,但尚未添加。检查此拉取请求 https://github.com/jhy/jsoup/pull/318 。你真的需要为此使用jsoup吗?我的意思是您可以使用HttpURLConnection(这是jsoup 在下面使用的)发出请求,然后将响应作为字符串传递给jsoup。

    这是从www.mkyong.com 获取的HttpURLConnection 示例(但简化并添加了 json/原始数据)

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

    【讨论】:

    • 这只是一个例子。它可以而且应该被清理干净。错误处理不存在。为了尽可能简单,我故意这样保留它。
    • 关于如何在不使用 JSoup 之类的库的情况下本地执行此操作的极简答案。我第一次尝试时对我来说效果很好。 +1
    【解决方案2】:

    使用最新的 JSOUP 库。

    如果您使用的是 maven,则将以下条目添加到 pom.xml

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

    下面的代码将解决您的问题。

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

    【讨论】:

    • 基于最新的1.11.3版本,我们需要使用“.method(Method.POST)”和“.requestBody(jsonPayload.toString())”。
    • .header("Accept", "application/json") .header("Content-Type", "application/json") 也是需要的!
    【解决方案3】:

    这就是我使用 jsoup v1.14.3Kotlin 的方式(也适用于 Java)。
    它发送两个参数 nameage 作为 JSON 对象的一部分(假设服务器接受):

    val document = Jsoup.connect("the/target/url")
        .userAgent("Mozilla")
        .header("content-type", "application/json")
        .header("accept", "application/json")
        .requestBody("""{"name": "Katy", "age": 43}""")
        .ignoreContentType(true)
        .post()
    

    您也可以在url-encoded format 中发送参数(假设服务器接受):

    val document = Jsoup.connect("the/target/url")
        .userAgent("Mozilla")
        .header("content-type", "application/x-www-form-urlencoded")
        .header("accept", "application/json")
        .data("name", "Katy")
        .data("age", "43")
        // OR
        //.data(mapOf("name" to "Katy", "age" to "43"))
        .ignoreContentType(true)
        .post()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多