HTTP接口开发专题二(发送http请求的接口工具类)

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
/**
* Http工具类*/
public class HttpUtils {
/**
* 解析出url参数中的键值对 如 "index.jsp?Action=del&id=123",解析出Action:del,id:123存入map中
*
* @param URL
* url地址
* @return url请求参数部分
*/
public static Map<String, String> URLRequest(String URL) {
Map<String, String> mapRequest = new HashMap<String, String>(); String[] arrSplit = null; String strUrlParam = truncateUrlPage(URL);
if (strUrlParam == null) {
return mapRequest;
}
// 每个键值为一组 www.2cto.com
arrSplit = strUrlParam.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]"); // 解析出键值
if (arrSplitEqual.length > 1) {
// 正确解析
mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]); } else {
if (arrSplitEqual[0] != "") {
// 只有参数没有值,不加入
mapRequest.put(arrSplitEqual[0], "");
}
}
}
return mapRequest;
} /**
* 发起HTTP POST请求。
* @param urlStr 请求URL
* @param params 请求参数
* @return 响应结果
*/
public static String post(String urlStr, Map<String, Object> params) {
URL url = null;
StringBuffer buff = new StringBuffer(""); HttpURLConnection urlConn = null;
OutputStream out = null;
BufferedReader in = null;
try {
Set<Entry<String, Object>> keySet = params.entrySet(); int i = 0;
//将map参数转换为 key1=value1&key2=value2 的形式
for (Iterator<Entry<String, Object>> iter = keySet.iterator(); iter.hasNext();) {
Entry<String,Object> entry = iter.next();
// 跳过值为null的参数
if(entry.getValue() == null) {
continue;
}
if (i > 0) {
buff.append("&");
}
buff.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
i++;
} url = new URL(urlStr);//把urlStr转变为URL类对象
       //用来解决对于https接口地址的访问
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. "
+ session.getPeerHost());
return true;
}
};
//访问https接口时,服务器不信任我们自己创建的证书,所以在代码中必须要忽略证书信任问题。只要在创建connection之前调用两个方法:
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(hv); urlConn = (HttpURLConnection) url.openConnection(); //打开URL连接
urlConn.setDefaultUseCaches(false); //post请求不能使用缓存
urlConn.setConnectTimeout(30000);
urlConn.setReadTimeout(60000);
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false); //post请求不能使用缓存
urlConn.setRequestProperty("Accept-Charset","UTF-8"); //设置编码方式
//没有设置内容类型,默认是Content-Type: application/x-www-form-urlencoded
out = urlConn.getOutputStream();
out.write(buff.toString().getBytes("UTF-8")); //请求体 in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
String data = "";
StringBuffer sb = new StringBuffer("");
while (null != (data = in.readLine())) {
sb.append(data);
} return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if(urlConn != null) {
urlConn.disconnect();
}
} return "";
}
/**
* 发起HTTP POST请求。
* @param urlStr 请求URL
* @param output POST数据,这里是json格式字符串
* @return 响应结果
*/
public static String post(String urlStr, String output) {
URL url = null; HttpURLConnection urlConn = null;
OutputStream out = null;
BufferedReader in = null;
try {
url = new URL(urlStr); urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDefaultUseCaches(false);
urlConn.setConnectTimeout(30000);
urlConn.setReadTimeout(60000);
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setRequestMethod("POST");
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Accept-Charset","UTF-8"); //HttpURLConnection.setRequestProperty(String key,String value);  设置http请求头,这里设置编码格式
urlConn.setRequestProperty("Content-Type", "application/json"); //设置内容类型:json格式
out = urlConn.getOutputStream();
out.write(output.getBytes("UTF-8")); in = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
String data = "";
StringBuffer sb = new StringBuffer("");
while (null != (data = in.readLine())) {
sb.append(data);
} return sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(out != null) {
out.close();
}
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if(urlConn != null) {
urlConn.disconnect();
}
} return "";
} //用来解决不能访问https请求的问题
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
}
//用来解决不能访问https请求的问题
private static class miTM implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
} public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
} public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
} public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
} public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
}
上一篇:字符设备之register_chrdev与register_chrdev_region(转)


下一篇:StringBuilder(字符串拼接类)