集册 Java实例教程 使用套接字发送POST请求

使用套接字发送POST请求

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

528
使用套接字发送POST请求

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;/**from N o w J a v a . c o m - 时代Java**/

import java.net.InetAddress;

import java.net.Socket;

import java.net.URLEncoder;


public class Main {

  void m() {

    try {

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

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


      // Create a socket to the host

      String hostname = "hostname.com";

      int port = 80;

      InetAddress addr = InetAddress.getByName(hostname);

      Socket socket = new Socket(addr, port);


      // Send header
      /*
      来 自*
       时代Java
      */

      String path = "/servlet/SomeServlet";

      BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));

      wr.write("POST " + path + " HTTP/1.0\r\n");

      wr.write("Content-Length: " + data.length() + "\r\n");

      wr.write("Content-Type: application/x-www-form-urlencoded\r\n");

      wr.write("\r\n");


      // Send data

      wr.write(data);

      wr.flush();


      // Get response

      
展开阅读全文