如何使用jsoup传递原始参数

时间:2022-08-14 20:21:22

I want to call an API which just accepts raw data when you send requests using jsoup.

我想在使用jsoup发送请求时调用一个只接受原始数据的API。

My code looks like this:

我的代码看起来像这样:

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

But I know the above code is not right for passing raw data.

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

Can anybody tell me how can I do it?

谁能告诉我怎么办呢?

1 个解决方案

#1


You'd have to use HttpUrlConnection to post the raw data to the website, and fetch the response as a String. Some Example, post data:

您必须使用HttpUrlConnection将原始数据发布到网站,并以String形式获取响应。一些例子,发布数据:

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

Getting response as String:

获得字符串响应:

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

To parse with Jsoup:

用Jsoup解析:

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

#1


You'd have to use HttpUrlConnection to post the raw data to the website, and fetch the response as a String. Some Example, post data:

您必须使用HttpUrlConnection将原始数据发布到网站,并以String形式获取响应。一些例子,发布数据:

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

Getting response as String:

获得字符串响应:

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

To parse with Jsoup:

用Jsoup解析:

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