Java URLConnection 实现 HTTP get与post
【摘要】
这几年来,Java 中对 Http 的请求涌现出许多框架,比如 OkHttp3、Retrofit2 等
在大部分情况下,使用这些第三方框架即可。但有的时候,我们必须使用原生的 HttpUrlConnec...
这几年来,Java 中对 Http 的请求涌现出许多框架,比如 OkHttp3、Retrofit2 等
在大部分情况下,使用这些第三方框架即可。但有的时候,我们必须使用原生的 HttpUrlConnection,例如 Android 5.0 (API 21)以下的设备
package com.demo.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HttpDemo {
static class HttpParamMap extends HashMap<String, String> {
private static final long serialVersionUID = 1L;
private static final String URL_ENCODE = "utf-8";
@Override
public String put(String key, String value) {
try {
key = URLEncoder.encode(key, URL_ENCODE);
value = URLEncoder.encode(key, URL_ENCODE);
return super.put(key, value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
@Override
public String toString() {
if (size() == 0) {
return "";
}
StringBuffer sb = new StringBuffer();
Set<Entry<String, String>> entrySet = entrySet();
Iterator<Entry<String, String>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
if (iterator.hasNext()) {
sb.append("&");
}
}
return sb.toString();
}
}
private static String httpGet(String urlStr, String params) {
BufferedReader br = null;
StringBuffer result = new StringBuffer();
if (!params.isEmpty()) {
urlStr += ("?" + params);
}
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// 设置通用请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.connect();
Map<String, List<String>> headerMap = conn.getHeaderFields();
Set<Entry<String, List<String>>> entrySet = headerMap.entrySet();
Iterator<Entry<String, List<String>>> iterator = entrySet.iterator();
while (iterator.hasNext()) {
Entry<String, List<String>> entry = iterator.next();
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
line = br.readLine();
while((line = br.readLine()) != null) {
result.append(line);
result.append(System.getProperty("line.separator"));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result.toString();
}
private static String httpPost(String urlStr, String params) {
PrintWriter pr = null;
StringBuffer result = new StringBuffer();
BufferedReader br = null;
if (!params.isEmpty()) {
urlStr += ("?" + params);
}
try {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
// 设置通用请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
pr = new PrintWriter(conn.getOutputStream());
pr.print(params);
pr.flush();
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while((line = br.readLine()) != null) {
result.append(line);
result.append(System.getProperty("line.separator"));
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(pr != null) {
//PrintWriter的close内部有try-catch
pr.close();
}
if(br != null) {
try {
//BufferedReader的内部仅有try-finally,没有catch错误,所以依旧会被抛出
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public static void main(String[] args) {
final String URL_ADDRESS = "http://localhost:8080";
HttpParamMap paramMap = new HttpParamMap();
paramMap.put("name", "chy龙神");
paramMap.put("password", "123456");
String param = paramMap.toString();
String getResult = httpGet(URL_ADDRESS, param);
String postResult = httpPost(URL_ADDRESS, param);
System.out.println("getResult = " + getResult);
System.out.println("postResult = " + postResult);
}
}
- 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
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
2020-05-07 补充
某次在使用 URLConnection 的时候遇到乱码了,经排查发现设置请求头导致的
httpURLConnection.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
- 1
当有配置 Accept-Encoding 时,服务器会按照顺序依次尝试压缩算法,对返回的数据进行压缩。最终服务端选择的压缩算法会写在 “Content-Encoding” 字段中,被包裹在 ResponseHeaders 中返回回来。如果返回的是 gzip 压缩后的数据,则从流中读取的内容必须经过 gzip 解压,否则就是乱码。
程序中为了图方便,而且数据量也少,自然不可能像浏览器做的那么周全,因此,不指明 “Accept-Encoding” 会让服务器默认以原始明文方式返回,这样就避免了解压这一步操作了。
文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/chy555chy/article/details/52511444
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)