Java使用HttpsURLConnection进行Get和Post请求(绕过证书验证)

来源:互联网 发布:淘宝怎么开手机充值店 编辑:程序博客网 时间:2024/06/05 13:10

工作中遇到使用HttpsURLConnection进行Get和Post请求时,报出javax.net.ssl.SSLHandshakeException异常,也就是证书验证问题,由于时间问题,在导入证书一直失败后,无奈选择绕过证书方式发送请求。。。

Get:

//与HttpURLConnection类似public String getconnbyget(String url){    StringBuilder result = new StringBuilder();try {URL u=new URL(url);HttpsURLConnection huconn=(HttpsURLConnection) u.openConnection();    //连接服务器              huconn.connect();              // 取得输入流,并使用Reader读取              BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));            String line;            while ((line = in.readLine()) != null) {            result.append(line);            }} catch (IOException e) {e.printStackTrace();}finally{            try{                if(in!=null){                    in.close();                }            }            catch(IOException ex){                ex.printStackTrace();            }        }return result.toString();}


Post:

public String gethttpsconnbypost(String url,Map headMap){    StringBuilder result = new StringBuilder();try {//创建地址对象URL u=new URL(url);//获取HttpURLConnection链接对象HttpURLConnection huconn=(HttpURLConnection) u.openConnection();//绕过证书验证,验证主机名和服务器验证方案的匹配是可接受的huconn.setHostnameVerifier(new CustomizedHostnameVerifier());// 发送POST请求必须设置如下两行,如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 falsehuconn.setDoOutput(true);//如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 truehuconn.setDoInput(true);//设置POST方式连接huconn.setRequestMethod("POST");//创建头信息map迭代器    Iterator it = headMap.keySet().iterator();    //设置请求头配置信息    while (it.hasNext()) {String key = it.next();String value = headMap.get(key);huconn.setRequestProperty(key, value);}//连接服务器          OutputStreamWriter out = new OutputStreamWriter(huconn.getOutputStream(),"UTF-8");        //写入请求体        out.write(data);        out.flush();        out.close();        // 取得输入流,并使用Reader读取,设定字符编码          BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));        String line;        while ((line = in.readLine()) != null) {            result.append(line);        }} catch (IOException e) {e.printStackTrace();}//关闭输入流        finally{            try{                if(in!=null){                    in.close();                }            }            catch(IOException ex){                ex.printStackTrace();            }        }return result.toString();}

验证证书类

import javax.net.ssl.HostnameVerifier;import javax.net.ssl.SSLSession;public class CustomizedHostnameVerifier implements HostnameVerifier{ //重写验证方法 @Override      public boolean verify(String arg0, SSLSession arg1)      {   //所有都正确        return true;      }   }


但最好还是使用导入证书方式



阅读全文
0 0
原创粉丝点击