要将数据传输到接受 POST 请求的服务器端脚本,例如“page.php”,请按照以下步骤操作:
请求初始化:
实例化一个URL 对象并打开连接:
URL aaa = new URL("http://www.example.com/page.php"); URLConnection ccc = aaa.openConnection();
POST 设置:
配置连接以允许 POST 数据提交:
ccc.setDoOutput(true); ccc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
查询参数编码:
转换请求参数(例如 id=10)到编码查询字符串中:
String data = "id=" + URLEncoder.encode("10", "UTF-8");
数据传输:
将数据写入连接的输出流:
OutputStreamWriter wr = new OutputStreamWriter(ccc.getOutputStream()); wr.write(data); wr.flush();
回复处理:
获取并处理服务器的响应:
BufferedReader br = new BufferedReader(new InputStreamReader(ccc.getInputStream())); String response = br.readLine();
更新的答案:
对于使用 Apache HTTP 组件的 Java 程序员,最新的方法涉及HttpClients和HttpPost。参数作为 NameValuePair 列表传递,编码为 UrlEncodedFormEntity,然后提交到服务器:
HttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost("http://www.a-domain.example/foo/"); List<NameValuePair> params = new ArrayList<>(2); params.add(new BasicNameValuePair("param-1", "12345")); params.add(new BasicNameValuePair("param-2", "Hello!")); httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream instream = entity.getContent()) { // Process the response here. } }
有关更多信息,请参阅 Apache HTTP 组件的文档。
以上是如何在Java中发送HTTP POST请求?的详细内容。更多信息请关注PHP中文网其他相关文章!