版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_19671783/article/details/78349583
1、创建get请求:
public static String doGet(String url, String charset)
throws IOException {
HttpURLConnection conn = null;
String rsp = null;
try {
String ctype = "application/x-www-form-urlencoded;charset=" + charset;
conn = getConnection(new URL(url), "GET", ctype);
rsp = getResponseAsString(conn);
} finally {
if (conn != null) {
conn.disconnect();
}
}
return rsp;
}
url为请求URL,charset为编码格式。
2、获取http连接
private static HttpURLConnection getConnection(URL url, String method, String ctype)
throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html,application/json");
conn.setRequestProperty("Content-Type", ctype);
conn.setConnectTimeout(5*60*1000);//连接超时
conn.setReadTimeout(5*60*1000);//读取数据超时
return conn;
}
method定义为GET或POST。
3、获取响应(字符串形式)
private static String getResponseAsString(HttpURLConnection conn) throws IOException {
String charset = getResponseCharset(conn.getContentType());
InputStream es = conn.getErrorStream();
if (es == null) {
return getStreamAsString(conn.getInputStream(), charset);
} else {
String msg = getStreamAsString(es, charset);
if (StringUtils.isEmpty(msg)) {
throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
}
4、获取响应的编码格式
private static String getResponseCharset(String ctype) {
String charset = "UTF-8";
if (!StringUtils.isEmpty(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!StringUtils.isEmpty(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
}
return charset;
}
5、通过输出流获取响应字符串
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
StringWriter writer = new StringWriter();
char[] chars = new char[1024];
int count = 0;
while ((count = reader.read(chars)) > 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}