用Java发送POST数据
问题描述:
我试图用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);
答
相同,但注释:
URL url = new URL("http://g.php"); // URL to your application
Map<String,Object> params = new LinkedHashMap<>();
params.put("value", 5); // All parameters, also easy
params.put("id", 17);
StringBuilder postData = new StringBuilder();
// POST as urlencoded is basically key-value pairs, as with GET
// This creates key=value&key=value&... pairs
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"));
}
// Convert string to byte array, as it should be sent
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
// Connect, easy
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
// Tell server that this is POST and in which format is the data
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);
// This gets the output from your server
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