簡體   English   中英

發送和接收HTTP發布數據-Java

[英]Sending and receiving HTTP post data - Java

我正在嘗試通過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());

錯誤在哪里?

移動這些行:

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

pout.close(); getInputStream方法實際上將HTTP請求發送到服務器,在該示例中,您是在填充正文之前發送請求的。

在此之后,似乎還有其他問題需要修復。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM