如何在Java中发送HTTP请求?

这个问题在这里已经有了答案:

  • 如何使用java.net.URLConnection来触发和处理HTTP请求12个答案

  • 你可以使用java.net.HttpUrlConnection。

    示例(从这里),有改进。 包含在链接的情况下:

    public static String executePost(String targetURL, String urlParameters) {
      HttpURLConnection connection = null;
    
      try {
        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", 
            "application/x-www-form-urlencoded");
    
        connection.setRequestProperty("Content-Length", 
            Integer.toString(urlParameters.getBytes().length));
        connection.setRequestProperty("Content-Language", "en-US");  
    
        connection.setUseCaches(false);
        connection.setDoOutput(true);
    
        //Send request
        DataOutputStream wr = new DataOutputStream (
            connection.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.close();
    
        //Get Response  
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
        String line;
        while ((line = rd.readLine()) != null) {
          response.append(line);
          response.append('r');
        }
        rd.close();
        return response.toString();
      } catch (Exception e) {
        e.printStackTrace();
        return null;
      } finally {
        if (connection != null) {
          connection.disconnect();
        }
      }
    }
    

    来自Oracle的java教程

    import java.net.*;
    import java.io.*;
    
    public class URLConnectionReader {
        public static void main(String[] args) throws Exception {
            URL yahoo = new URL("http://www.yahoo.com/");
            URLConnection yc = yahoo.openConnection();
            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(
                                    yc.getInputStream()));
            String inputLine;
    
            while ((inputLine = in.readLine()) != null) 
                System.out.println(inputLine);
            in.close();
        }
    }
    

    我知道其他人会推荐Apache的http客户端,但它增加了很少担保的复杂性(即更多可能出错的事情)。 对于一个简单的任务, java.net.URL会做。

    URL url = new URL("http://www.y.com/url");
    InputStream is = url.openStream();
    try {
      /* Now read the retrieved document from the stream. */
      ...
    } finally {
      is.close();
    }
    
    链接地址: http://www.djcxy.com/p/15927.html

    上一篇: How to send HTTP request in java?

    下一篇: HTTP GET request in JavaScript?