具体的看代码吧:代码即文档
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* http请求
*
* @author taihei
*
*/
public class MyHttpReq {
/**
* GET请求 (自动识别是否使用SSL)
* @param uri 网址(完整路径,可拼接参数)
* @param params (可为null)
* @return
*/
public static String httpGetReq(String uri, Map<String, Object> params) {
if (null == uri || uri.replace(" ", "").length() < 10
|| (!uri.startsWith("http://") && !uri.startsWith("https://"))) {//一个合法的网址至少为10位(需以http开头)
return "error:URI非法";
}
uri = paramsHandle4Get(uri, params);
try {
URL url = new URL(uri);
//p判断是否需要https请求
if (uri.startsWith("https://")) {
SSLSocketFactory sslf = defaultSSLFactory();
HttpsURLConnection urlSslConnection = (HttpsURLConnection) url.openConnection();
urlSslConnection.setSSLSocketFactory(sslf);
urlSslConnection.setRequestMethod("GET");
urlSslConnection.setRequestProperty("Accept", "application/json");
return returnDataHandle4UrlSSLConnection(urlSslConnection);
} else {
// 打开连接 HttpURLConnection是URLConnection的子类
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//默认返回值格式为json
urlConnection.setRequestProperty("Accept", "application/json");
return returnDataHandle4UrlConnection(urlConnection);
}
} catch (IOException e) {
e.printStackTrace();
}
return "error: 请求失败";
}
/**
* 对get请求的参数进行Url拼接处理
* @param uri
* @param params
* @return
*/
private static String paramsHandle4Get(String uri, Map<String, Object> params) {
// 对参数进行处理
if (null != params && !params.isEmpty()) {
Set<String> ks = params.keySet();
StringBuilder sb = new StringBuilder();
for (String key : ks) {
try {
sb.append(key + "=" + URLEncoder.encode(params.get(key).toString(), "UTF-8") + "&");//内容用url编码
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
String pj = sb.substring(0, sb.length() - 1);
if (pj.length() > 0) {
if (uri.contains("?")) {
uri = uri + "&" + pj;
} else {
uri = uri + "?" + pj;
}
}
}
return uri;
}
/**
*
* post请求(自动识别是否用ssl请求)
*
*
* @param uri 请求地址
* @param content 内容(json格式)
* @return (若请求失败,则返回以 "error:"为开头的字符串)
*/
public static String httpPostReq(String uri, String content) {
if (null == uri || uri.replace(" ", "").length() < 10
|| (!uri.startsWith("http://") && !uri.startsWith("https://"))) {//一个合法的网址至少为10位(需以http开头)
return "error:URI非法";
}
try {
URL url = new URL(uri);
//判断是否要求https请求
if (uri.startsWith("https://")) {
SSLSocketFactory sslf = defaultSSLFactory();
HttpsURLConnection urlSslConnection = (HttpsURLConnection) url.openConnection();
urlSslConnection.setSSLSocketFactory(sslf);
urlSslConnection.setRequestMethod("POST");
urlSslConnection.setDoInput(true);
urlSslConnection.setDoOutput(true);
urlSslConnection.setUseCaches(false);// Post 请求不使用缓存
urlSslConnection.setRequestProperty("Accept", "application/json");//优先接收json数据
urlSslConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//form表单提交
// 如果需要发送数据
if (null != content && content.trim().length() > 0) {
PrintWriter printWriter = new PrintWriter(urlSslConnection.getOutputStream());
printWriter.write(content);
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
}
return returnDataHandle4UrlSSLConnection(urlSslConnection);
} else {
// 打开连接 HttpURLConnection是URLConnection的子类
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);// Post 请求不使用缓存
// urlConnection.setRequestProperty("Accept", "application/xhtml+xml");//xml格式返回值
//默认返回值格式为json
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 如果需要发送数据
if (null != content && content.length() > 0) {
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
// 发送请求参数
printWriter.write(content);
// flush输出流的缓冲
printWriter.flush();
}
return returnDataHandle4UrlConnection(urlConnection);
}
} catch (IOException e) {
e.printStackTrace();
}
return "error:请求失败";
}
/**
* 读取输入流内的数据
* @param is
* @return
* @throws IOException
*/
private static ByteArrayOutputStream getInputDataFromInputStrem(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = is.read(buffer))) {
baos.write(buffer, 0, len);
baos.flush();
}
is.close();
return baos;
}
/**
* post请求(自动识别是否用ssl请求)
*
* @param uri 请求地址
* @param params 参数 可为null
* @return (若请求失败,则返回以 "error:"为开头的字符串)
*/
public static String httpPostReq(String uri, Map<String, Object> params) {
if (null == uri || uri.replace(" ", "").length() < 10
|| (!uri.startsWith("http://") && !uri.startsWith("https://"))) {//一个合法的网址至少为10位(需以http开头)
return "error:URI非法";
}
try {
URL url = new URL(uri);
//判断是否要求https请求
if (uri.startsWith("https://")) {
SSLSocketFactory sslf = defaultSSLFactory();
HttpsURLConnection urlSslConnection = (HttpsURLConnection) url.openConnection();
urlSslConnection.setSSLSocketFactory(sslf);
urlSslConnection.setRequestMethod("POST");
urlSslConnection.setDoInput(true);
urlSslConnection.setDoOutput(true);
urlSslConnection.setUseCaches(false);// Post 请求不使用缓存
urlSslConnection.setRequestProperty("Accept", "application/json");//优先接收json数据
urlSslConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//form表单提交
// 如果需要发送数据
if (null != params && !params.isEmpty()) {
PrintWriter printWriter = new PrintWriter(urlSslConnection.getOutputStream());
printWriter.write(params.toString().replaceAll("[{|}]", ""));
// flush输出流的缓冲
printWriter.flush();
printWriter.close();
}
return returnDataHandle4UrlSSLConnection(urlSslConnection);
} else {
// 打开连接 HttpURLConnection是URLConnection的子类
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
// 发送POST请求必须设置如下两行
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);// Post 请求不使用缓存
// urlConnection.setRequestProperty("Accept", "application/xhtml+xml");//xml格式返回值
//默认返回值格式为json
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 如果需要发送数据
if (null != params && !params.isEmpty()) {
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(urlConnection.getOutputStream());
// 发送请求参数
printWriter.write(params.toString().replaceAll("[{|}]", ""));
// flush输出流的缓冲
printWriter.flush();
}
return returnDataHandle4UrlConnection(urlConnection);
}
} catch (IOException e) {
e.printStackTrace();
}
return "error:请求失败";
}
/**
* 处理https请求返回值
* @param urlSslConnection
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static String returnDataHandle4UrlSSLConnection(HttpsURLConnection urlSslConnection)
throws IOException, UnsupportedEncodingException {
if (200 == urlSslConnection.getResponseCode()) {
// 得到输入流
InputStream is = urlSslConnection.getInputStream();
ByteArrayOutputStream baos = getInputDataFromInputStrem(is);
urlSslConnection.disconnect();
return baos.toString("utf-8");
} else {
return "error: " + urlSslConnection.getResponseCode();
}
}
/**
* 处理http请求返回
* @param urlConnection
* @return
* @throws IOException
* @throws UnsupportedEncodingException
*/
private static String returnDataHandle4UrlConnection(HttpURLConnection urlConnection)
throws IOException, UnsupportedEncodingException {
if (200 == urlConnection.getResponseCode()) {
// 得到输入流
InputStream is = urlConnection.getInputStream();
ByteArrayOutputStream baos = getInputDataFromInputStrem(is);
urlConnection.disconnect();// 数据读取完毕关闭流
return baos.toString("utf-8");
} else {
return "error: " + urlConnection.getResponseCode();
}
}
/**
* 创建一个默认的ssl工厂,(接受所有证书)
* @return
*/
public static SSLSocketFactory defaultSSLFactory() {
X509TrustManager x509TrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
};
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { x509TrustManager }, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
}
return ssfFactory;
}
}
其实这里面得代码还能再进行封装,