简体   繁体   中英

Sending and receiving HTTP post data - Java

I'm trying to send a request through Google's Safe Browsing API, but I'm not getting any output and I'm not sure why. I've searched this online but each solution either only refers to only how to send or receive a POST request (but not both), or the input of data is done differently.

According to the Google Safe Browsing documentation:

Specify the queried URLs in the POST request body using the following format:

POST_REQ_BODY = NUM LF URL (LF URL)* NUM = (DIGIT)+ URL = URL string following the RFC 1738

-

Response body:

POST_RESP_BODY = VERDICT (LF VERDICT)* VERDICT = “phishing” | “malware” | "unwanted" | “phishing,malware” >| "phishing,unwanted" | "malware,unwanted" | "phishing, malware, unwanted" >| “ok”

and sent to:

https://sb-ssl.google.com/safebrowsing/api/lookup?client=CLIENT&key=APIKEY

I found another topic that shows how you send this request, but I'm not sure how to get/print out the response. Here is what I tried:

String baseURL="https://sb-ssl.google.com/safebrowsing/api/lookup";
String arguments = "";
arguments +=URLEncoder.encode("client", "UTF-8") + "=" + URLEncoder.encode("myapp", "UTF-8") + "&";
arguments +=URLEncoder.encode("apikey", "UTF-8") + "=" + URLEncoder.encode("12345", "UTF-8") + "&";
arguments +=URLEncoder.encode("appver", "UTF-8") + "=" + URLEncoder.encode("1.5.2", "UTF-8") + "&";
arguments +=URLEncoder.encode("pver", "UTF-8") + "=" + URLEncoder.encode("3.0", "UTF-8");

// Construct the url object representing cgi script
URL url = new URL(baseURL + "?" + arguments);

// Get a URLConnection object, to write to POST method
URLConnection connect = url.openConnection();

// Specify connection settings
connect.setDoInput(true);
connect.setDoOutput(true);

InputStream input = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;

// Get an output stream for writing
OutputStream output = connect.getOutputStream();
PrintStream pout = new PrintStream (output);
pout.print("2");
pout.println();
pout.print("http://www.google.com");
pout.println();
pout.print("http://www.facebook.com");
pout.close();

while((line = reader.readLine()) != null) {
   result.append(line);
}
System.out.println(result.toString());

Where is the error?

Move these lines:

InputStream input = connect.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));

After pout.close(); , the getInputStream method actually send the HTTP request to the server, in that example you are sending the request before you fill the body.

It looks like there will be other things to fix after this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM