请告诉我如何使用请求方法PUT或DELETE在jsoup中创建http(s)请求?
我遇到了这个链接: https://github.com/jhy/jsoup/issues/158 但它已有几年历史了,所以希望在该图书馆中实施一些宁静的支持。
据我所知,HttpConnection对象我只能使用'get'或'post'请求方法。
http://jsoup.org/apidocs/org/jsoup/helper/HttpConnection.html
答案 0 :(得分:1)
Jsoup不支持PUT或DELETE方法。由于它是解析器,因此不需要支持这些操作。你可以做的是使用HttpURLConnection
,这与Jsoup在下面使用的相同。有了这个,你可以使用你想要的任何方法,最后用jsoup解析结果(如果你真的需要它)。
检查此代码:
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 rawData = "RAW_DATA_HERE";
String url = "URL_HERE";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("METHOD_HERE"); //e.g POST
con.setRequestProperty("KEY_HERE", "VALUE_HERE"); //e.g key = Accept, value = application/json
con.setDoOutput(true);
OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
w.write(rawData);
w.close();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response code : " + responseCode);
System.out.println(response.toString());
//Use Jsoup on response to parse it if it makes your work easier.
} catch(Exception e) {
e.printStackTrace();
}
}
}