httpGet + hostname in certificate didn't match 报错!
HTTPS加密引起的。
Hostname in certificate didn't match?
两种方式:
GET、SET
try { String strRequest=cdoRequest.toXML(); String strTransName = cdoRequest.getStringValue("strTransName"); String _strURL = strUrl + "?strTransName=" + strTransName + "&$$CDORequest$$=" + java.net.URLEncoder.encode(strRequest,"UTF-8"); if(_strURL.length()>=1024) { httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST); Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("strTransName",cdoRequest.getStringValue("strTransName")); paramMap.put("$$CDORequest$$",strRequest); httpClient.setUrl(strUrl); httpClient.setNameValuePair(paramMap); } else { httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_GET); httpClient.setUrl(_strURL); } strCDOXml = httpClient.getResponseString(); }catch(Exception ex) { logger.error(ex.getMessage(), ex); return Return.valueOf(-1," http Status:"+httpClient.getStatus()+";Send Http Request ERROR:"+ex.getMessage()); }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLConnection; import java.util.Map; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.log4j.Logger; public class HttpUtil { private static final Logger logger = Logger.getLogger(HttpUtil.class); /** * http post请求 * @param url 地址 * @param postContent post内容格式为param1=value¶m2=value2¶m3=value3 * @return * @throws IOException */ public static String httpPostRequest(URL url, String postContent) throws Exception{ OutputStream outputstream = null; BufferedReader in = null; try { URLConnection httpurlconnection = url.openConnection(); httpurlconnection.setConnectTimeout(10 * 1000); httpurlconnection.setDoOutput(true); httpurlconnection.setUseCaches(false); OutputStreamWriter out = new OutputStreamWriter(httpurlconnection .getOutputStream(), "UTF-8"); out.write(postContent); out.flush(); StringBuffer result = new StringBuffer(); in = new BufferedReader(new InputStreamReader(httpurlconnection .getInputStream(),"UTF-8")); String line; while ((line = in.readLine()) != null) { result.append(line); } return result.toString(); } catch(Exception ex){ logger.error("post请求异常:" + ex.getMessage()); throw new Exception("post请求异常:" + ex.getMessage()); } finally { if (outputstream != null) { try { outputstream.close(); } catch (IOException e) { outputstream = null; } } if (in != null) { try { in.close(); } catch (IOException e) { in = null; } } } } /** * 通过httpClient进行post提交 * @param url 提交url地址 * @param charset 字符集 * @param keys 参数名 * @param values 参数值 * @return * @throws Exception */ public static String HttpClientPost(String url , String charset , String[] keys , String[] values) throws Exception{ HttpClient client = null; PostMethod post = null; String result = ""; int status = 200; try { client = new HttpClient(); //PostMethod对象用于存放地址 //总账户的测试方法 post = new PostMethod(url); //NameValuePair数组对象用于传入参数 post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=" + charset);//在头文件中设置转码 String key = ""; String value = ""; NameValuePair temp = null; NameValuePair[] params = new NameValuePair[keys.length]; for (int i = 0; i < keys.length; i++) { key = (String)keys[i]; value = (String)values[i]; temp = new NameValuePair(key , value); params[i] = temp; temp = null; } post.setRequestBody(params); //执行的状态 status = client.executeMethod(post); logger.info("status = " + status); if(status == 200){ result = post.getResponseBodyAsString(); } } catch (Exception ex) { // TODO: handle exception throw new Exception("通过httpClient进行post提交异常:" + ex.getMessage() + " status = " + status); } finally{ post.releaseConnection(); } return result; } /** * 字符串处理,如果输入字符串为null则返回"",否则返回本字符串去前后空格。 * @param inputStr 输入字符串 * @return string 输出字符串 */ public static String doString(String inputStr){ //如果为null返回"" if(inputStr == null || "".equals(inputStr) || "null".equals(inputStr)){ return ""; } //否则返回本字符串把前后空格去掉 return inputStr.trim(); } /** * 对象处理,如果输入对象为null返回"",否则则返回本字符对象信息,去掉前后空格 * @param object * @return */ public static String doString(Object object){ //如果为null返回"" if(object == null || "null".equals(object) || "".equals(object)){ return ""; } //否则返回本字符串把前后空格去掉 return object.toString().trim(); } }
使用:
String returnXML = HttpUtil.httpPostRequest(new URL(sendURL), postContent);
工具类2:
public class HttpUtil { private static Log log = LogFactory.getLog(HttpUtil.class); private static final String DEFAULT_HTTP_CHARSET = "UTF-8"; private static final String GETID_URL = ProPertiesUtil.getValue("/server.properties", "getidurl"); private static DefaultHttpClient httpClient = new DefaultHttpClient(); private HttpUtil() {} public static String sendHttpByPost(String url,Map map) throws Exception{ HttpClient httpClient = new HttpClient(HttpClient.TRANSMODE_FORM,HttpClient.METHOD_POST); /*Map<String,String> paramMap = new HashMap<String,String>(); paramMap.put("wf_type_id",wf_type_id.toString()); paramMap.put("customer_id",customer_id.toString()); paramMap.put("thirdparty_id",thirdparty_id.toString()); paramMap.put("order_no",order_no); paramMap.put("order_idss",order_idss); paramMap.put("user_id",user_id.toString()); paramMap.put("wf_code",wf_code); paramMap.put("step",step.toString()); paramMap.put("wf_id", wf_id.toString());*/ httpClient.setUrl(url); httpClient.setNameValuePair(map); return httpClient.getResponseString(); } public static String httpGet(String url) { String strReturn = ""; HttpUriRequest request = new HttpGet(url); try { HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); strReturn = EntityUtils.toString(entity,DEFAULT_HTTP_CHARSET); }catch(Exception e) { // 网络异常 log.error(e.getMessage()); } return strReturn; } public static void main(String[] args) throws JSONException, Exception{ String strUrl1 = "http://localhost:8084/test/order/addOrder.do?orderCode=123456789&totalFee=39800"; System.out.println(httpGet(strUrl1)); } }
或:
public String getMedia(String token,String mediaID){ logger.info("getMedia=============start"); String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+token+"&media_id="+mediaID; BufferedInputStream bis = null; FileOutputStream fos = null; String imgFilePath = null; try { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse response = client.execute(httpGet); HttpEntity entity = response.getEntity(); // 根据内容类型获取扩展名 String fileExt = getFileEndWitsh(entity.getContentType().getValue()); if(StringUtils.isEmpty(fileExt)) { logger.error("上传图片出错:content-Type" +entity.getContentType().getValue() + EntityUtils.toString(entity, "UTF-8")); return null; } String tmpImgPath = ProPertiesUtil.getValue("/auction.properties", "tmp_img_path"); imgFilePath = getPhysicalPath(tmpImgPath) + File.separator + mediaID + fileExt;;// 新生成的图片 bis = new BufferedInputStream(entity.getContent()); fos = new FileOutputStream(new File(imgFilePath)); byte[] buf = new byte[8096]; int size = 0; while ((size = bis.read(buf)) != -1) fos.write(buf, 0, size); fos.close(); bis.close(); logger.info("下载媒体文件成功,filePath="+ imgFilePath); } catch (Exception e) { imgFilePath = null; logger.error("下载媒体文件失败:",e); } finally { if (bis != null) { try { bis.close(); } catch (IOException e) { logger.error("连接微信出错:",e); } } if (fos != null) { try { fos.close(); } catch (IOException e) { logger.error("连接微信出错:",e); } } } return imgFilePath; }
HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(IMAGE_FTP_PATH); File file = new File(filePath); FileBody fileBody = new FileBody(file); try { MultipartEntity entity = new MultipartEntity(); entity.addPart("file", fileBody); post.setEntity(entity); HttpResponse response = httpclient.execute(post); logger.info("图片服务器返回code:" + response.getStatusLine().getStatusCode()); if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) { HttpEntity entitys = response.getEntity(); if (entitys != null) { //resultLen = entity.getContentLength(); returnStr = EntityUtils.toString(entitys); logger.info("图片服务器返回returnStr:" + returnStr); } } httpclient.getConnectionManager().shutdown(); //删除本地 //file.delete(); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); } catch (ClientProtocolException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); }
3、
package com.common.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.util.Map; /** * @author Administrator * */ public class HttpUtils { /** * 使用Get方式获取数据 * * @param url * URL包括参数,http://HOST/XX?XX=XX&XXX=XXX * @param charset * @return */ public static String sendGet(String url) { String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection .getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * POST请求,字符串形式数据 * @param url 请求地址 * @param param 请求数据 * @param charset 编码方式 */ public static String sendPostUrl(String url, String param, String charset) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( conn.getInputStream(), charset)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * POST请求,Map形式数据 * @param url 请求地址 * @param param 请求数据 * @param charset 编码方式 */ public static String sendPost(String url, Map<String, String> param, String charset) { StringBuffer buffer = new StringBuffer(); if (param != null && !param.isEmpty()) { for (Map.Entry<String, String> entry : param.entrySet()) { buffer.append(entry.getKey()).append("=").append( URLEncoder.encode(entry.getValue())).append("&"); } } buffer.deleteCharAt(buffer.length() - 1); PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(buffer); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( conn.getInputStream(), charset)); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } public static void main(String[] args) { } }
工具类3:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; public class HttpRequest { // private static Logger logger = Logger.getLogger(HttpRequest.class); /** * 向指定URL发送GET方法的请求 * * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); // logger.error("连接出错",e); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { // logger.error("连接出错",e2); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("Content-Type", "application/json;charset=utf-8"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 OutputStream outputStream = conn.getOutputStream(); String aa = new String(param.getBytes("UTF8"),"UTF8"); System.out.println("=========== "+aa); out = new PrintWriter(outputStream); // 发送请求参数 out.print(aa); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!"+e); //logger.error("连接出错",e); } //使用finally块来关闭输出流、输入流 finally{ try{ if(out!=null){ out.close(); } if(in!=null){ in.close(); } } catch(IOException ex){ // logger.error("连接出错",ex); } } return result; } }
工具类4:
相关推荐
HttpUtils 发送 HTTP 请求工具类详解 HTTP 请求工具类是 Java 语言中一个常用的工具类,用于发送 HTTP 请求并处理响应结果。本文将对 HttpUtils 发送 HTTP 请求工具类进行详细的讲解,包括其实现原理、关键代码分析...
org.springframework.web.client.AsyncRestTemplate org.springframework.web.client.RestTemplate HTTP请求工具类,基于以上两个Rest请求工具模板完成封装HTTP请求,包括同步和异步请求的实现。
在IT行业中,HTTP请求工具类是开发者经常使用的工具,它简化了向服务器发送HTTP请求的过程。这个名为"HttpUtil"的Java文件很可能是为开发者提供一个便捷的接口,用于执行GET、POST等常见的HTTP方法。下面我们将深入...
请求http工具 支持ssl,请求参数支持json数据和map数据,能自动转换编码),不必担心返回数据乱码
首先,`HttpUtil`类通常用于封装HTTP请求的操作。在Java中,我们可以使用`java.net.HttpURLConnection`或`org.apache.http.client.HttpClient`(Apache HttpClient库)来发送HTTP请求。这两个方法各有优劣:`...
Android自定义网络连接工具类HttpUtil是一个非常实用的网络连接类库,它提供了发送GET和POST请求的功能,并且可以接收服务器端发送过来的JSON字符串数据。下面是对HttpUtil类的详细介绍和解释。 类结构 HttpUtil类...
`HttpUtil` 是一个工具类,通常用于简化Java开发中的HTTP请求操作,尤其是对于POST请求的处理。在这个特定的场景中,`HttpUtil` 针对两种常见的HTTP请求类型——data-form(表单数据)和SSL(安全套接层)进行了优化...
http连接请求,可以支持请求get,post方式请求表单,支持上传文件
首先,我们来看`HttpUtils`类,这是核心的网络请求工具类。在`HttpUtils`中,通常会包含两个主要方法:`sendGetRequest`和`sendPostRequest`,分别用于执行GET和POST请求。 1. **GET请求**: - GET请求常用于获取...
java http工具,包括get、post、json格式请求,使用httpclient
在这个过程中,`HttpUtil.java`可能是一个自定义的工具类,包含了使用`httpclient`进行HTTP操作的实用方法。它可能会包含创建`HttpClient`、构建请求、解析响应等功能,简化了代码的复用和维护。 总之,`httpclient...
"httpUtils请求工具类"是一个常见的Java库,用于简化HTTP请求操作,特别是GET和POST方法。这个工具类使得开发者无需深入了解底层HTTP协议,就能轻松地发送数据到服务器并获取响应。下面我们将深入探讨这个工具类以及...
在IT行业中,工具类是程序员经常使用的一种设计模式,它封装了特定功能,方便在项目中重复使用。这里提到的"HttpUtil工具包"显然是一款针对HTTP网络请求的实用工具,它提供了对字符串和图片处理的功能。让我们深入...
HttpClient远程调用工具类 get 和post 调用用访问别的系统接口 用http方式请求,包括调用时用的工具类
HttpUtil工具类主要用于处理HTTP请求和响应,它简化了网络通信过程。开发者可以利用HttpUtil发送GET、POST等请求,设置请求头,处理响应数据等。这个工具类通常会包含如`sendGetRequest`和`sendPostRequest`这样的...
用于HTTP请求的工具类,支持GET,POST,HTTP,HTTPS 代码简单易懂
非常齐全的http工具类,可以发送/接收各种请求。包括文件的发送,获取,带token验证的请求等
模拟http请求实现文件上传,模拟doGet、doPost请求,实现信息发送