集册 Java实例教程 使用URL发送POST请求

使用URL发送POST请求

欢马劈雪     最近更新时间:2020-01-02 10:19:05

507
使用URL发送POST请求

import java.io.BufferedReader;

import java.io.InputStreamReader;
/** 
 来自 时代Java公众号 - N o w J a  v a . c o m**/

import java.io.OutputStreamWriter;

import java.net.URL;

import java.net.URLConnection;

import java.net.URLEncoder;


public class Main {


  public void main(String[] argv) {

    try {

      // Construct data

      String data = URLEncoder.encode("key1", "UTF-8") + "="

          + URLEncoder.encode("value1", "UTF-8");

      data += "&" + URLEncoder.encode("key2", "UTF-8") + "="

          + URLEncoder.encode("value2", "UTF-8");


      // Send data
      /** 
       来自 时 代 J a v a 公 众 号 - nowjava.com**/

      URL url = new URL("http://hostname:80/cgi");

      URLConnection conn = url.openConnection();

      conn.setDoOutput(true);

      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());

      wr.write(data);

      wr.flush();


      // Get the response

      BufferedReader rd = new BufferedReader(new 
展开阅读全文