我正在使用 HTTP 参数向服务器发送查询并获取结果。我使用 Jsoup 并在 URL 中发送我的参数:
String doc = Jsoup.connect("http://server.com/query?a=x").execute().body();
但是,在某些情况下,我不想要结果。我只想将参数发送到服务器并忽略响应。
有没有办法阻止 Jsoup 下载响应?有没有其他方法可以在不下载响应的情况下将 HTTP URL 参数发送到服务器?
我正在使用 HTTP 参数向服务器发送查询并获取结果。我使用 Jsoup 并在 URL 中发送我的参数:
String doc = Jsoup.connect("http://server.com/query?a=x").execute().body();
但是,在某些情况下,我不想要结果。我只想将参数发送到服务器并忽略响应。
有没有办法阻止 Jsoup 下载响应?有没有其他方法可以在不下载响应的情况下将 HTTP URL 参数发送到服务器?
Jsoup 在下面使用 HttpURLConnection。省略响应不是一个选项,也不应该是,因为它是一个解析框架。否则没有任何意义。您可以做的是直接使用 HttpURLConnection 发送请求,然后您就不会阅读响应。以下是从此处获取的 POST 和 GET 示例
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpURLConnectionExample http = new HttpURLConnectionExample();
System.out.println("Testing 1 - Send Http GET request");
http.sendGet();
System.out.println("\nTesting 2 - Send Http POST request");
http.sendPost();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "http://www.google.com/search?q=mkyong";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
/*This part should be removed*/
/*BufferedReader in = new BufferedReader(
//new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString()); */
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
/*This part should be removed*/
/*BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());*/
}
}