使用浏览器来发送http/https来发送请求是常用的操作,那么在Java的使用又是怎样的呢?
本例演示在java中来发送get/post请求的来获取reponse.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package com.devnp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpURLConnectionDemo {

public static void main(String[] args) throws IOException {

// send get
sendGet();

//send post
sendPost();
}

public static void sendGet() throws IOException {
String url = "http://www.devnp.com/?s=duliu";

URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// optional default is GET
con.setRequestMethod("GET");

// add request header
con.setRequestProperty("User-Agent", "Mozilla/5.0");

int responseCode = con.getResponseCode();

System.err.println("response code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}

in.close();

// print result
System.out.println(response.toString());
}

public static void sendPost() throws IOException {
String url = "http://www.devnp.com/";

URL obj = new URL(url);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "s=duliu";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();

System.err.println("response code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());
}
}