关于html:如何在java中发送HTTP请求?

How to send HTTP request in java?

本问题已经有最佳答案,请猛点这里访问。

在Java中,如何编写HTTP请求消息并将其发送到HTTP Web服务器?


你可以使用java.net.httpurlconnection。

一个例子,(从这里)的改进。案例链接:包括在红色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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('
'
);
    }
    rd.close();
    return response.toString();
  } catch (Exception e) {
    e.printStackTrace();
    return null;
  } finally {
    if (connection != null) {
      connection.disconnect();
    }
  }
}


从甲骨文的Java教程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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客户端,但它的复杂性(即,添加更多的事情可以去错了)这是warranted很少。一个简单的任务,java.net.URL想做的。

1
2
3
4
5
6
7
8
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();
}


httpcomponents Apache。这两个模块的例子,你想和httpcore HttpClient开始吧。

这是一个坏的选择httpurlconnection困境,httpcomponents想摘要焊料的tedious编码了。我会推荐这个,如果你真的想了很多支持HTTP服务器/客户端与最小的代码。顺便说一下,httpcore可以用于应用程序(客户端或服务器)与最小的功能,而HttpClient是用于客户端的认证计划,要求支持多支持,饼干等。


这是一个完整的Java程序:7

1
2
3
4
5
6
7
class GETHTTPResource {
  public static void main(String[] args) throws Exception {
    try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
      System.out.println(s.useDelimiter("\\A").next());
    }
  }
}

新的尝试与资源要自动关闭扫描仪,这将自动关闭InputStream。


这将帮助你。不要忘记添加到classpath HttpClient.jar的JAR。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class MainSendRequest {

     static String url =
        "http://localhost:8080/HttpRequestSample/RequestSend.jsp";

    public static void main(String[] args) {

        //Instantiate an HttpClient
        HttpClient client = new HttpClient();

        //Instantiate a GET HTTP method
        PostMethod method = new PostMethod(url);
        method.setRequestHeader("Content-type",
               "text/xml; charset=ISO-8859-1");

        //Define name-value pairs to set into the QueryString
        NameValuePair nvp1= new NameValuePair("firstName","fname");
        NameValuePair nvp2= new NameValuePair("lastName","lname");
        NameValuePair nvp3= new NameValuePair("email","[email protected]");

        method.setQueryString(new NameValuePair[]{nvp1,nvp2,nvp3});

        try{
            int statusCode = client.executeMethod(method);

            System.out.println("Status Code ="+statusCode);
            System.out.println("QueryString>>>"+method.getQueryString());
            System.out.println("Status Text>>>"
                  +HttpStatus.getStatusText(statusCode));

            //Get data as a String
            System.out.println(method.getResponseBodyAsString());

            //OR as a byte array
            byte [] res  = method.getResponseBody();

            //write to file
            FileOutputStream fos= new FileOutputStream("donepage.html");
            fos.write(res);

            //release connection
            method.releaseConnection();
        }
        catch(IOException e) {
            e.printStackTrace();
        }
    }
}


谷歌的Java API for HTTP客户端的HTTP请求有很好。你可以很容易添加JSON支持等。虽然它的简单请求可能是多余的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import java.io.IOException;
import java.io.InputStream;

public class Network {

    static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

    public void getRequest(String reqUrl) throws IOException {
        GenericUrl url = new GenericUrl(reqUrl);
        HttpRequest request = HTTP_TRANSPORT.createRequestFactory().buildGetRequest(url);
        HttpResponse response = request.execute();
        System.out.println(response.getStatusCode());

        InputStream is = response.getContent();
        int ch;
        while ((ch = is.read()) != -1) {
            System.out.print((char) ch);
        }
        response.disconnect();
    }
}


你可以使用这个类插座

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
String host ="www.yourhost.com";
Socket socket = new Socket(host, 80);
String request ="GET / HTTP/1.0



"
;
OutputStream os = socket.getOutputStream();
os.write(request.getBytes());
os.flush();

InputStream is = socket.getInputStream();
int ch;
while( (ch=is.read())!= -1)
    System.out.print((char)ch);
socket.close();


有一个伟大的链接请求发送邮件的例子在这里::由仓库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
    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 InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

如果你想发送一个GET请求,你可以修改代码以适合你的需要的时间。特别是你添加在构造函数的参数的URL。然后,所以我出本wr.write(data);

一个写的东西不是你应该当心,是超时。特别是如果你想使用它,你必须集中服务超时,如果上面的代码要等待很长的时间indefinitely或至少与它的东西presumably你不想要的。

一个这样的conn.setReadTimeout(2000);超时设置输入参数是在milliseconds