English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

java to simulate http Get/Post request, and set ip and port proxy method

This article involves3Some basic points:

1, because many company internal networks have set up proxy servers, browsers access the internet through IP and port, and Java code simulating HTTP GET also needs an external network proxy;

2, Java implementation of HTTP Get/Post request code;

3, mainly to set the properties in the HTTPURLConnection header

For example: Cookie, User-Agent (browser type) and so on.

For example: adding Header in HTTP requests

conn.setRequestProperty("Authorization", authorization);

注:我就在网上找的一段Get/Post模拟请求代码,添加了下代理的配置,整合完成的。

package com.pasier.quanzi.web.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class HttpRequest {
  public static void main(String[] args) {
    // 如果不设置,只要代理IP和代理端口正确,此项不设置也可以
    System.getProperties().setProperty("http.proxyHost", "10.22.40.32");
    System.getProperties().setProperty("http.proxyPort", "8080");
    // 判断代理是否设置成功
    // 发送 GET 请求
    System.out.println(sendGet(
        "http://www.baidu.com",
        "param1=xxx¶m2=yyy"));
    // 发送 POST 请求
  }
  /**
   * 向指定URL发送GET方法的请求
   * 
   * Send a POST method request to the specified URL
   *      发送请求的URL
   * @param param
   *      Request parameters, the request parameters should be name1=value1&name2=value2 in the form of.
   * @return URL 所代表远程资源的响应结果
   */
  public static String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
      String urlNameString = url + "?" + param;
      URL realUrl = new URL(urlNameString);
      // Open connection with URL
      URLConnection connection = realUrl.openConnection();
      // Set general request properties
      connection.setRequestProperty("accept", "*/*");
      connection.setRequestProperty("connection", "Keep Alive", "第2段": "connection.setRequestProperty("accept", "", "第3段": "URLConnection connection = realUrl.openConnection();", "第4段": "URL realUrl = new URL(urlNameString);", "第5段": "param;", "第6段": ";\"", "第7段": "\"&#", "第8段": "String urlNameString = url", "第9段": "public static String sendGet(String url, String param) {", "第10段": "@return URL represents the response result of the remote resource", "第11段": "Sending request URL", "第12段": "Send a GET method request to the specified URL", "第13段": "Send POST request", "第14段": "=yyy\"));", "第15段": "=xxx¶m", "第16段": "\"param", "第17段": "www.baidu.com\", "第18段": "\"http:\", "第19段": "System.out.println(sendGet(", "第20段": "Send GET request", "第21段": "Determine if the proxy is set successfully", "第22段": "0\");", "第23段": "System.getProperties().setProperty("http.proxyPort", "", "第24段": "0.", "第25段": "System.getProperties().setProperty("http.proxyHost", "", "第26段": "If not set, as long as the proxy IP and proxy port are correct, this item can also be not set", "第27段": "public static void main(String[] args) {", "第28段": "public class HttpRequest {", "第29段": "import java.util.Map;", "第30段": "import java.util.List;", "第31段": "import java.net.URLConnection;", "第32段": "import java.net.URL;", "第33段": "import java.io.PrintWriter;", "第34段": "import java.io.InputStreamReader;", "第35段": "import java.io.IOException;", "第36段": "import java.io.BufferedReader;", "第37段": "package com.pasier.quanzi.web.controller;", "第38段": "Post simulation request code, added proxy configuration, integrated completion.", "第39段": "Note: This is a piece of Get code I found on the Internet."-Alive");
      connection.setRequestProperty("user"-agent",
          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
      // Establish the actual connection
      connection.connect();
      // Get all response header fields
      Map<String, List<String>> map = connection.getHeaderFields();
      // Traverse all the response header fields
      for (String key : map.keySet()) {
        System.out.println(key + "---">" + map.get(key));
      }
      // Define BufferedReader input stream to read the response of URL
      in = new BufferedReader(new InputStreamReader(
          connection.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("An exception occurred while sending GET request!") + e);
      e.printStackTrace();
    }
    // Use the finally block to close the input stream
    finally {
      try {
        if (in != null) {
          in.close();
        }
      catch (Exception e2}
        ) {2e
      }
    }
    return result;
  }
  /**
   * e.printStackTrace();
   * 
   * Send a POST method request to the specified URL
   *      @param url
   * @param param
   *      Request parameters, the request parameters should be name1=value1&name2=value2 in the form of.
   * @return The response result of the represented remote resource
   */
  public static String sendPost(String url, String param) {
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
      URL realUrl = new URL(url);
      // Open connection with URL
      URLConnection conn = realUrl.openConnection();
      // Set general request properties
      conn.setRequestProperty("accept", "*/*");
      conn.setRequestProperty("connection", "Keep-Alive");
      conn.setRequestProperty("user-agent",
          "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
      // The following two lines must be set when sending a POST request
      conn.setDoOutput(true);
      conn.setDoInput(true);
      // Get the output stream of the URLConnection object
      out = new PrintWriter(conn.getOutputStream());
      // Send request parameters
      out.print(param);
      // Flush the buffer of the output stream
      out.flush();
      // Define a BufferedReader input stream to read the response of the URL
      in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        result += line;
      }
    } catch (Exception e) {
      System.out.println("An exception occurred while sending a POST request!") + e);
      e.printStackTrace();
    }
    // Use the finally block to close the output stream and input stream
    finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (IOException ex) {
        ex.printStackTrace();
      }
    }
    return result;
  }
}

The above Java simulation of http Get/The method of setting ip and port proxy for Post request is all the editor shares with everyone, hoping it can provide a reference for everyone, and also hope everyone will support the呐喊 tutorial more.

You may also like