我試圖用POST提交表單。我想發送一些值並將它們存儲在Web服務器上的一個SQL數據庫中。我在堆棧中發現了這個例子,但是我沒有正確理解它。用Java發送POST數據
URL應該引用接受POST請求的php文件嗎?其他值在這裏我必須考慮。我geuss的參數是好的,他們應該匹配我的PHP文件上的POST檢查。
這是成功發送數據與POST從Java到我的網絡服務器所需的全部嗎?
URL url = new URL("http://g.php");
Map<String,Object> params = new LinkedHashMap<>();
params.put("value", 5);
params.put("id", 17);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c; (c = in.read()) >= 0;)
System.out.print((char)c);
Java是不是一個縮寫。 – shmosel
固定。謝謝你的觀察 – brondy