HTTPS请求工具类.docx
《HTTPS请求工具类.docx》由会员分享,可在线阅读,更多相关《HTTPS请求工具类.docx(14页珍藏版)》请在冰豆网上搜索。
HTTPS请求工具类
HTTPS请求
packagecom.sunzk.dreamsunlight.weixin.util;
importjava.io.BufferedReader;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.OutputStream;
import.ConnectException;
import.URL;
import.ssl.HttpsURLConnection;
import.ssl.SSLContext;
import.ssl.SSLSocketFactory;
import.ssl.TrustManager;
importnet.sf.json.JSONException;
importnet.sf.json.JSONObject;
importorg.apache.log4j.Logger;
importcom.sunzk.dreamsunlight.weixin.certificate.MyX509TrustManager;
importcom.sunzk.dreamsunlight.weixin.model.Menu;
importcom.sunzk.dreamsunlight.weixin.token.AccessToken;
/**
*
*@ClassName:
WeiXinHttpsUtil
*
*@Description:
TODO(微信HTTPS请求工具类)
*
*@authorsunzk-dreamsunlight-QQ(1131341075)
*
*@date2016-11-14上午10:
05:
56
*
*/
publicclassWeiXinHttpsUtil{
privatestaticLoggerlogger=Logger.getLogger(WeiXinHttpsUtil.class);
//获取access_token的接口地址(GET)限200(次/天)
publicfinalstaticStringaccess_token_url="";
/**
*发起https请求并获取结果
*
*@paramrequestUrl请求地址
*@paramrequestMethod请求方式(GET、POST)
*@paramoutputStr提交的数据
*@returnJSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
publicstaticJSONObjecthttpRequest(StringrequestUrl,StringrequestMethod,StringoutputStr){
JSONObjectjsonObject=null;
StringBufferbuffer=newStringBuffer();
try{
//创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[]tm={newMyX509TrustManager()};
SSLContextsslContext=SSLContext.getInstance("SSL","SunJSSE");
sslContext.init(null,tm,newjava.security.SecureRandom());
//从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactoryssf=sslContext.getSocketFactory();
URLurl=newURL(requestUrl);
HttpsURLConnectionhttpUrlConn=(HttpsURLConnection)url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
//设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
//当有数据需要提交时
if(null!
=outputStr){
OutputStreamoutputStream=httpUrlConn.getOutputStream();
//注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
//将返回的输入流转换成字符串
InputStreaminputStream=httpUrlConn.getInputStream();
InputStreamReaderinputStreamReader=newInputStreamReader(inputStream,"UTF-8");
BufferedReaderbufferedReader=newBufferedReader(inputStreamReader);
Stringstr=null;
while((str=bufferedReader.readLine())!
=null){
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
//释放资源
inputStream.close();
inputStream=null;
httpUrlConn.disconnect();
jsonObject=JSONUtils.toJSONObject(buffer.toString());
}catch(ConnectExceptionce){
logger.info("Weixinserverconnectiontimedout.");
}catch(Exceptione){
logger.info("httpsrequesterror:
{}",e);
}
returnjsonObject;
}
/**
*获取access_token
*
*@paramappid凭证
*@paramappsecret密钥
*@return
*/
publicstaticAccessTokengetAccessToken(Stringappid,Stringappsecret){
AccessTokenaccessToken=null;
StringrequestUrl=access_token_url.replace("APPID",appid).replace("APPSECRET",appsecret);
JSONObjectjsonObject=httpRequest(requestUrl,"GET",null);
//如果请求成功
if(null!
=jsonObject){
try{
accessToken=newAccessToken();
accessToken.setAccess_token(jsonObject.getString("access_token"));
accessToken.setExpires_in(jsonObject.getInt("expires_in"));
}catch(JSONExceptione){
logger.info("获取token失败errcode:
{}errmsg:
{}"+jsonObject.getInt("errcode")+jsonObject.getString("errmsg"));
accessToken=null;//获取token失败
}
}
returnaccessToken;
}
publicstaticvoidmain(String[]args){
Stringurl="";
StringrequestMethod="GET";
JSONObjectobj=httpRequest(url,requestMethod,null);
Stringinfo=JSONUtils.toJSONString(obj);
System.out.println("<------返回信息------>"+info);
}
}
HTTP请求
packagecom.sunzk.dreamsunlight.weixin.util;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.io.PrintWriter;
import.URL;
import.URLConnection;
import.URLEncoder;
importjava.util.Map;
/**
*
*@ClassName:
HttpUtil
*
*@Description:
TODO(HttpRequest请求工具类)
*
*@authorsunzk-dreamsunlight-QQ(1131341075)
*
*@date2016-11-11上午10:
44:
44
*
*/
publicclassHttpUtil{
/**
*使用Get方式获取数据
*
*@paramurl
*URL包括参数,
*@paramcharset
*@return
*/
publicstaticStringsendGet(Stringurl,Stringcharset){
Stringresult="";
BufferedReaderin=null;
try{
URLrealUrl=newURL(url);
//打开和URL之间的连接
URLConnectionconnection=realUrl.openConnection();
//设置通用的请求属性
connection.setRequestProperty("accept","*/*");
connection.setRequestProperty("connection","Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//建立实际的连接
connection.connect();
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(newInputStreamReader(
connection.getInputStream(),charset));
Stringline;
while((line=in.readLine())!
=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送GET请求出现异常!
"+e);
e.printStackTrace();
}
//使用finally块来关闭输入流
finally{
try{
if(in!
=null){
in.close();
}
}catch(Exceptione2){
e2.printStackTrace();
}
}
returnresult;
}
/**
*POST请求,字符串形式数据
*@paramurl请求地址
*@paramparam请求数据
*@paramcharset编码方式
*/
publicstaticStringsendPostUrl(Stringurl,Stringparam,Stringcharset){
PrintWriterout=null;
BufferedReaderin=null;
Stringresult="";
try{
URLrealUrl=newURL(url);
//打开和URL之间的连接
URLConnectionconn=realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out=newPrintWriter(conn.getOutputStream());
//发送请求参数
out.print(param);
//flush输出流的缓冲
out.flush();
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(newInputStreamReader(
conn.getInputStream(),charset));
Stringline;
while((line=in.readLine())!
=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送POST请求出现异常!
"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!
=null){
out.close();
}
if(in!
=null){
in.close();
}
}catch(IOExceptionex){
ex.printStackTrace();
}
}
returnresult;
}
/**
*POST请求,Map形式数据
*@paramurl请求地址
*@paramparam请求数据
*@paramcharset编码方式
*/
publicstaticStringsendPost(Stringurl,Mapparam,
Stringcharset){
StringBufferbuffer=newStringBuffer();
if(param!
=null&&!
param.isEmpty()){
for(Map.Entryentry:
param.entrySet()){
buffer.append(entry.getKey()).append("=")
.append(URLEncoder.encode(entry.getValue()))
.append("&");
}
}
buffer.deleteCharAt(buffer.length()-1);
PrintWriterout=null;
BufferedReaderin=null;
Stringresult="";
try{
URLrealUrl=newURL(url);
//打开和URL之间的连接
URLConnectionconn=realUrl.openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out=newPrintWriter(conn.getOutputStream());
//发送请求参数
out.print(buffer);
//flush输出流的缓冲
out.flush();
//定义BufferedReader输入流来读取URL的响应
in=newBufferedReader(newInputStreamReader(
conn.getInputStream(),charset));
Stringline;
while((line=in.readLine())!
=null){
result+=line;
}
}catch(Exceptione){
System.out.println("发送POST请求出现异常!
"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!
=null){
out.close();
}
if(in!
=null){
in.close();
}
}catch(IOExceptionex){
ex.printStackTrace();
}
}
returnresult;
}
publicstaticvoidmain(String[]args){
Stringurl="";
Stringencode="GB2312";
Stringcontent=sendGet(url,encode);
System.out.println("<-------------HttpRquest请求结果-------------->"+content);
}
}