发送和接收HTTP发布数据 - Java

时间:2015-07-01 14:13:07

标签: java http urlconnection

我正在尝试通过Google的安全浏览API发送请求,但我没有得到任何输出,我不知道为什么。我在网上搜索了这个,但是每个解决方案或者只是指如何发送或接收POST请求(但不是两者),或者数据的输入是以不同方式完成的。

根据Google安全浏览文档:

  

使用以下格式在POST请求正文中指定查询的URL:

     

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

-

  

回复机构:

     

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

并发送至:

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

我找到另一个主题,显示您如何发送此请求,但我不确定如何获取/打印响应。这是我试过的:

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

错误在哪里?

1 个答案:

答案 0 :(得分:1)

移动以下行:

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

pout.close();之后,getInputStream方法实际上将HTTP请求发送到服务器,在该示例中,您在填充正文之前发送请求。

看起来在此之后还有其他事情需要解决。