如何使用jsoup传递原始参数

How to pass raw parameter using jsoup

我想调用一个 API,当您使用 jsoup 发送请求时它只接受原始数据。

我的代码如下所示:

Document res = Jsoup.connect(url)
        .header("Accept", "application/json")
        .header("X-Requested-With", "XMLHttpRequest")
        .data("name", "test", "room", "bedroom")
        .post();

但我知道上面的代码不适合传递原始数据。

谁能告诉我该怎么做?

您必须使用 HttpUrlConnection 将原始数据 post 发送到网站,并以字符串形式获取响应。一些示例,post 数据:

HttpUrlConnection conn = new URL("http://somesite.com/").openConnection();
String str =  "some string goes here";  //use a String for our raw data
byte[] outputInBytes = str.getBytes("UTF-8");  //byte array with raw data
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );    

获取字符串形式的响应:

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));

StringBuilder response = new StringBuilder();
String inputLine;

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

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

使用 Jsoup 解析:

Document doc = Jsoup.parse(response.toString());