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
private void GetRequest(String url){
HttpURLConnection connection=null;
try {
URL url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(1000);
connection.setReadTimeout(1000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP error code" + responseCode);
}
String result = getStringByStream(connection.getInputStream());
...
}
catch (Exception e) {
...
}
}

private void PostRequest(String url, String param){
HttpURLConnection connection = null;
try {
URL url = new URL(url);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
connection.setRequestProperty("Content-Type", "application/json"); // 设置内容类型
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(false);
connection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("param", param);
OutputStream os = connection.getOutputStream();
byte[] input = jsonParam.toString().getBytes("utf-8");
os.write(input, 0, input.length);
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP error code" + responseCode);
}
String result = getStringByStream(connection.getInputStream());
...
}
catch (Exception e) {
...
}
}

private String getStringByStream(InputStream inputStream){
Reader reader;
try {
reader=new InputStreamReader(inputStream,"UTF-8");
char[] rawBuffer=new char[512];
StringBuffer buffer=new StringBuffer();
int length;
while ((length=reader.read(rawBuffer))!=-1){
buffer.append(rawBuffer,0,length);
}
return buffer.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}