發送http請求

    public static String httpGetSend(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET請求try {// http超時5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 設置 get 請求超時為 5 秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());httpClient.executeMethod(getMethod);// 發送請求// 讀取內容byte[] responseBody = getMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");} catch (Exception e) {Logger.getLogger(HttpUtils.class).error(e.getMessage());e.printStackTrace();} finally {getMethod.releaseConnection();// 關閉連接
        }return responseMsg;}

?

 /*** 發送HTTP請求* * @param url* @param propsMap*            發送的參數*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求//        postMethod.// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 發送請求
//            Log.info(postMethod.getStatusCode());// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}
 /*** 發送HTTP請求* * @param url* @param propsMap 發送的參數* @throws IOException*/private String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key) == null ? null : propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 發送請求// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容// responseMsg = URLDecoder.decode(new String(responseBody),// "UTF-8");responseMsg = new String(responseBody, "UTF-8");} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}

?

?

?

package com.huayuan.wap.common.utils;import java.io.IOException;
import java.util.Map;
import java.util.Set;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;import com.huayuan.wap.common.model.HttpResponse;public class HttpUtils {/*** 發送HTTP請求** @param url* @param propsMap 發送的參數*/public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求if (propsMap != null) {// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);}postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");try {int statusCode = httpClient.executeMethod(postMethod);// 發送請求
            response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }response.setContent(responseMsg);return response;}/*** 發送HTTP請求** @param url*/public static HttpResponse httpGet(String url) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);try {int statusCode = httpClient.executeMethod(getMethod);// 發送請求
            response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 讀取內容byte[] responseBody = getMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {getMethod.releaseConnection();// 關閉連接
        }response.setContent(responseMsg);return response;}
}
package com.j1.mai.util;import java.io.IOException;
import java.util.Map;
import java.util.Set;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;public class HttpUtils {/*** 發送HTTP請求** @param url* @param propsMap 發送的參數*/public static HttpResponse httpPost(String url, Map<String, Object> propsMap) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求if (propsMap != null) {// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);}postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");try {int statusCode = httpClient.executeMethod(postMethod);// 發送請求
            response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }response.setContent(responseMsg);return response;}/*** 發送HTTP請求** @param url*/public static HttpResponse httpGet(String url) {HttpResponse response = new HttpResponse();String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);try {int statusCode = httpClient.executeMethod(getMethod);// 發送請求
            response.setStatusCode(statusCode);if (statusCode == HttpStatus.SC_OK) {// 讀取內容byte[] responseBody = getMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");}} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {getMethod.releaseConnection();// 關閉連接
        }response.setContent(responseMsg);return response;}/*** 發送HTTP--GET請求* * @param url* @param propsMap*            發送的參數*/public static String httpGetSend(String url) {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET請求try {// http超時5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);// 設置 get 請求超時為 5 秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());httpClient.executeMethod(getMethod);// 發送請求// 讀取內容byte[] responseBody = getMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "utf-8");} catch (Exception e) {Logger.getLogger(HttpUtils.class).error(e.getMessage());e.printStackTrace();} finally {getMethod.releaseConnection();// 關閉連接
        }return responseMsg;}/*** 發送HTTP請求* * @param url* @param propsMap*            發送的參數*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求//        postMethod.// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 發送請求
//            Log.info(postMethod.getStatusCode());// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}/*** 發送Post HTTP請求* * @param url* @param propsMap*            發送的參數* @throws IOException * @throws HttpException */public static PostMethod httpSendPost(String url, Map<String, Object> propsMap,String authrition) throws Exception {HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求postMethod.addRequestHeader("Authorization",authrition);postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  // 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);httpClient.executeMethod(postMethod);// 發送請求return postMethod;}/*** 發送Post HTTP請求* * @param url* @param propsMap*            發送的參數* @throws IOException * @throws HttpException */public static PostMethod httpSendPost(String url, Map<String, Object> propsMap) throws Exception {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  // 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);httpClient.executeMethod(postMethod);// 發送請求return postMethod;}/*** 發送Get HTTP請求* * @param url* @param propsMap*            發送的參數* @throws IOException * @throws HttpException */public static GetMethod httpSendGet(String url, Map<String, Object> propsMap) throws Exception {String responseMsg = "";HttpClient httpClient = new HttpClient();GetMethod getMethod = new GetMethod(url);// GET請求getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  // 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {getMethod.getParams().setParameter(key, propsMap.get(key).toString());}httpClient.executeMethod(getMethod);// 發送請求return getMethod;}}
package com.founder.ec.member.util;import java.io.IOException;
import java.util.Map;
import java.util.Set;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;public class HttpUtils {/*** 發送HTTP請求* * @param url* @param propsMap*            發送的參數*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 發送請求// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody);} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}
}
package com.founder.ec.dec.util;import java.io.IOException;import lombok.extern.log4j.Log4j;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;/*** http請求實體類* * @author Yang Yang 2015年11月13日 下午5:20:43* @since 1.0.0*/
public class HttpUtils {/*** post發送http請求* * @param url* @param data* @return*/public static String sendHttpPost(String url, String data) {Logger log = Logger.getRootLogger();String responseMsg = "";HttpClient httpClient = new HttpClient();httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");PostMethod postMethod = new PostMethod(url);// POST請求// 參數設置postMethod.addParameter("param", data);try {httpClient.executeMethod(postMethod);// 發送請求// 讀取內容byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容responseMsg = new String(responseBody, "UTF-8");} catch (HttpException e) {log.error(e.getMessage());} catch (IOException e) {log.error(e.getMessage());} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}
}
package com.founder.ec.web.util.payments.yeepay;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
/**** <p>Title: </p>* <p>Description: http utils </p>* <p>Copyright: Copyright (c) 2006</p>* <p>Company: </p>* @author LiLu* @version 1.0*/
public class HttpUtils {private static final String URL_PARAM_CONNECT_FLAG = "&";private static final int SIZE     = 1024 * 1024;private static Log log = LogFactory.getLog(HttpUtils.class);private HttpUtils() {}/*** GET METHOD* @param strUrl String* @param map Map* @throws java.io.IOException* @return List*/public static List URLGet(String strUrl, Map map) throws IOException {String strtTotalURL = "";List result = new ArrayList();if(strtTotalURL.indexOf("?") == -1) {strtTotalURL = strUrl + "?" + getUrl(map);} else {strtTotalURL = strUrl + "&" + getUrl(map);}
//    System.out.println("strtTotalURL:" + strtTotalURL);URL url = new URL(strtTotalURL);HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setUseCaches(false);con.setFollowRedirects(true);BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()),SIZE);while (true) {String line = in.readLine();if (line == null) {break;}else {result.add(line);}}in.close();return (result);}/*** POST METHOD* @param strUrl String* @param content Map* @throws java.io.IOException* @return List*/public static List URLPost(String strUrl, Map map) throws IOException {String content = "";content = getUrl(map);String totalURL = null;if(strUrl.indexOf("?") == -1) {totalURL = strUrl + "?" + content;} else {totalURL = strUrl + "&" + content;}URL url = new URL(strUrl);HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setDoInput(true);con.setDoOutput(true);con.setAllowUserInteraction(false);con.setUseCaches(false);con.setRequestMethod("POST");con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=GBK");BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));bout.write(content);bout.flush();bout.close();BufferedReader bin = new BufferedReader(new InputStreamReader(con.getInputStream()),SIZE);List result = new ArrayList(); while (true) {String line = bin.readLine();if (line == null) {break;}else {result.add(line);}}return (result);}/*** ���URL* @param map Map* @return String*/private static String getUrl(Map map) {if (null == map || map.keySet().size() == 0) {return ("");}StringBuffer url = new StringBuffer();Set keys = map.keySet();for (Iterator i = keys.iterator(); i.hasNext(); ) {String key = String.valueOf(i.next());if (map.containsKey(key)) {Object val = map.get(key);String str = val!=null?val.toString():"";try {str = URLEncoder.encode(str, "GBK");} catch (UnsupportedEncodingException e) {e.printStackTrace();}url.append(key).append("=").append(str).append(URL_PARAM_CONNECT_FLAG);}}String strURL = "";strURL = url.toString();if (URL_PARAM_CONNECT_FLAG.equals("" + strURL.charAt(strURL.length() - 1))) {strURL = strURL.substring(0, strURL.length() - 1);}return (strURL);}/*** http 發送方法* @param strUrl 請求URL* @param content 請求內容* @return 響應內容* @throws org.apache.commons.httpclient.HttpException* @throws java.io.IOException*/public static String post(String strUrl,String content)throws IOException {URL url = new URL(strUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setDoOutput(true);connection.setDoInput(true);connection.setRequestMethod("POST");connection.setUseCaches(false);connection.setInstanceFollowRedirects(true);connection.setRequestProperty("Content-Type","text/plain;charset=UTF-8");connection.connect();// POST請求DataOutputStream out = new DataOutputStream(connection.getOutputStream());out.write(content.getBytes("utf-8"));out.flush();out.close();// 讀取響應BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));String lines;StringBuffer sb = new StringBuffer("");while ((lines = reader.readLine()) != null) {lines = new String(lines.getBytes(), "utf-8");sb.append(lines);}reader.close();// 斷開連接
    connection.disconnect();return sb.toString();}}
package com.founder.ec.utils;import net.sf.json.JSONObject;import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;public class HttpsUtils {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}/*** post方式請求服務器(https協議)** @param url*            請求地址* @param content*            參數* @param charset*            編碼* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/@SuppressWarnings("static-access")public static String post(String url, Map<String, Object> content, String charset)throws NoSuchAlgorithmException, KeyManagementException,IOException {String responseContent = null;SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();JSONObject obj = new JSONObject();obj = obj.fromObject(content);byte[] b = obj.toString().getBytes();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(b, 0, b.length);// 刷新、關閉
        out.flush();out.close();InputStream in = conn.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(in,"UTF-8"));String tempLine = rd.readLine();StringBuffer tempStr = new StringBuffer();String crlf=System.getProperty("line.separator");while (tempLine != null){tempStr.append(tempLine);tempStr.append(crlf);tempLine = rd.readLine();}responseContent = tempStr.toString();rd.close();in.close();if (conn != null){conn.disconnect();}return responseContent;}}
package com.founder.ec.web.util;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import net.sf.json.JSONObject;public class HttpsUtils {private static class TrustAnyTrustManager implements X509TrustManager {public void checkClientTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType)throws CertificateException {}public X509Certificate[] getAcceptedIssuers() {return new X509Certificate[] {};}}private static class TrustAnyHostnameVerifier implements HostnameVerifier {public boolean verify(String hostname, SSLSession session) {return true;}}/*** post方式請求服務器(https協議)** @param url*            請求地址* @param content*            參數* @param charset*            編碼* @return* @throws NoSuchAlgorithmException* @throws KeyManagementException* @throws IOException*/@SuppressWarnings("static-access")public static String post(String url, Map<String, Object> content, String charset)throws NoSuchAlgorithmException, KeyManagementException,IOException {String responseContent = null;SSLContext sc = SSLContext.getInstance("SSL");sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom());URL console = new URL(url);HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();conn.setSSLSocketFactory(sc.getSocketFactory());conn.setHostnameVerifier(new TrustAnyHostnameVerifier());conn.setDoOutput(true);conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");conn.connect();JSONObject obj = new JSONObject();obj = obj.fromObject(content);byte[] b = obj.toString().getBytes();DataOutputStream out = new DataOutputStream(conn.getOutputStream());out.write(b, 0, b.length);// 刷新、關閉
        out.flush();out.close();InputStream in = conn.getInputStream();BufferedReader rd = new BufferedReader(new InputStreamReader(in,"UTF-8"));String tempLine = rd.readLine();StringBuffer tempStr = new StringBuffer();String crlf=System.getProperty("line.separator");while (tempLine != null){tempStr.append(tempLine);tempStr.append(crlf);tempLine = rd.readLine();}responseContent = tempStr.toString();rd.close();in.close();if (conn != null){conn.disconnect();}return responseContent;}}
/*** 華潤通聯合登陸*//****聯合登錄獲取華潤通的用戶信息** appid,* access_token,* openid,* sign,* timestamp,* 通過code獲取token 與openId*/@RequestMapping(value = "/getHrtCode")public String hrt(HttpServletRequest request, HttpServletResponse response,String code,String state)  {JSONObject object = new JSONObject();JSONObject data = new JSONObject();String memberKey="";/**** 讀取配置文件拿到華潤通數據*/String hrtUrl=PropertyConfigurer.getString("hrtUrl");if(StringUtil.isEmpty(hrtUrl)){hrtUrl = "https://oauth2.huaruntong.cn/oauth2/access_token";}String hrtAppId=PropertyConfigurer.getString("hrtAppId");if(StringUtil.isEmpty(hrtAppId)){hrtAppId = "1655100000004";}String hrtSignKey=PropertyConfigurer.getString("hrtSignKey");if(StringUtil.isEmpty(hrtSignKey)){hrtSignKey = "tmKBcdNCTeyvDLTQFkYtbDdHBUwHZEmSZlNFbUhxHqQOjgev";}// //獲取當前時間SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");String timestamp= sd.format(new Date());String sign = "appid="+hrtAppId+"&code="+code+"&grant_type=authorization_code&timestamp="+timestamp+"&app_secret="+hrtSignKey;sign = MD5.getMD5(sign).toUpperCase();/***發送請求*/try {Map<String,Object> map = new HashMap<String , Object>();map.put("appid", hrtAppId);map.put("gant_type", grantType);map.put("code", code);map.put("timestamp", timestamp);map.put("sign",sign);String back = HttpsUtils.post(hrtUrl, map, "UTF-8");if(!back.isEmpty() || back!=null){object=  JSONObject.fromObject(back);data= object.getJSONObject("data");if( data.size()!=0 ){String openId= data.getString("openid");// 異常處理if (null == openId || "".equals(openId) ) {request.setAttribute("errors", "授權失敗,請重新授權!");return "/jsp/common/404.jsp";}ServiceMessage<com.j1.member.model.Member> result= memberSsoService.hrtFastLogin(openId);if(result.getStatus() == MsgStatus.NORMAL){com.j1.member.model.Member member= result.getResult();memberKey = result.getResult().getMemberKey();if(member!=null){request.getSession().setAttribute("memberId", member.getMemberId());request.getSession().setAttribute("loginName", member.getLoginName());request.getSession().setAttribute("realName", member.getRealName());request.getSession().setAttribute("member", member);request.getSession().setAttribute("mobile",member.getMobile());request.getSession().setAttribute("memberKey", result.getResult().getMemberKey());return "redirect:https://www.j1.com?memberKey"+memberKey;}}}}} catch (Exception e) {e.printStackTrace();logger.error("華瑞通系統內部報錯");}return "redirect:https://www.j1.com?memberKey"+memberKey;}

?

package com.founder.ec.web.util.payments.payeco.http;import com.founder.ec.web.util.payments.payeco.http.ssl.SslConnection;import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.SortedMap;/*** 描述: http通訊基礎類* */
public class HttpClient {private int status;public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public static String REQUEST_METHOD_GET = "GET";public static String REQUEST_METHOD_POST = "POST";public  String send(String postURL, String requestBody,String sendCharset, String readCharset) {return send(postURL,requestBody,sendCharset,readCharset,300,300);}public  String send(String postURL, String requestBody,String sendCharset, String readCharset,String RequestMethod) {return send(postURL,requestBody,sendCharset,readCharset,300,300,RequestMethod);}/*** @param postURL  訪問地址* @param requestBody  paramName1=paramValue1&paramName2=paramValue2* @param sendCharset  發送字符編碼* @param readCharset  返回字符編碼* @param connectTimeout  連接主機的超時時間 單位:秒* @param readTimeout 從主機讀取數據的超時時間 單位:秒* @return 通訊返回*/public  String send(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout) {try {return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,REQUEST_METHOD_POST);} catch (Exception ex) {ex.printStackTrace();System.out.print("發送請求[" + url + "]失敗," + ex.getMessage());return null;} }/*** @param postURL  訪問地址* @param requestBody  paramName1=paramValue1&paramName2=paramValue2* @param sendCharset  發送字符編碼* @param readCharset  返回字符編碼* @param connectTimeout  連接主機的超時時間 單位:秒* @param readTimeout 從主機讀取數據的超時時間 單位:秒* @param RequestMethod GET或POST* @return 通訊返回*/public  String send(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod) {try {return connection(url,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,RequestMethod);} catch (Exception ex) {ex.printStackTrace();System.out.print("發送請求[" + url + "]失敗," + ex.getMessage());return null;} }public  String connection(String postURL, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,String RequestMethod)throws Exception {if(REQUEST_METHOD_POST.equals(RequestMethod)){return postConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);}else if(REQUEST_METHOD_GET.equals(RequestMethod)){return getConnection(postURL,requestBody,sendCharset,readCharset,connectTimeout,readTimeout,null);}else{return "";}}@SuppressWarnings("rawtypes")public  String getConnection(String url, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {// Post請求的url,與get不同的是不需要帶參數HttpURLConnection httpConn = null;try {if (!url.contains("https:")) {URL postUrl = new URL(url);// 打開連接httpConn = (HttpURLConnection) postUrl.openConnection();} else {SslConnection urlConnect = new SslConnection();httpConn = (HttpURLConnection) urlConnect.openConnection(url);}httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + sendCharset);if(reqHead!=null&&reqHead.size()>0){Iterator iterator =reqHead.keySet().iterator();while (iterator.hasNext()) {String key = (String) iterator.next();String val = (String)reqHead.get(key);httpConn.setRequestProperty(key,val);}}// 設定傳送的內容類型是可序列化的java對象 // (如果不設此項,在傳送序列化對象時,當WEB服務默認的不是這種類型時可能拋java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); 
//            連接主機的超時時間(單位:毫秒)httpConn.setConnectTimeout(1000 * connectTimeout);
//            從主機讀取數據的超時時間(單位:毫秒) httpConn.setReadTimeout(1000 * readTimeout);// 連接,從postUrl.openConnection()至此的配置必須要在 connect之前完成,// 要注意的是connection.getOutputStream會隱含的進行 connect。
            httpConn.connect();int status = httpConn.getResponseCode();setStatus(status);if (status != HttpURLConnection.HTTP_OK) {System.out.print("發送請求失敗,狀態碼:[" + status + "] 返回信息:"+ httpConn.getResponseMessage());return null;}BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), readCharset));StringBuffer responseSb = new StringBuffer();String line = null;while ((line = reader.readLine()) != null) {responseSb.append(line.trim());}reader.close();return responseSb.toString().trim();} finally {httpConn.disconnect();}}@SuppressWarnings("rawtypes")public  String postConnection(String postURL, String requestBody,String sendCharset, String readCharset,int connectTimeout,int readTimeout,SortedMap reqHead)throws Exception {// Post請求的url,與get不同的是不需要帶參數HttpURLConnection httpConn = null;try {if (!postURL.contains("https:")) {URL postUrl = new URL(postURL);// 打開連接httpConn = (HttpURLConnection) postUrl.openConnection();} else {SslConnection urlConnect = new SslConnection();httpConn = (HttpURLConnection) urlConnect.openConnection(postURL);}//             設置是否向httpUrlConnection輸出,因為這個是post請求,參數要放在 
//             http正文內,因此需要設為true, 默認情況下是false; httpConn.setDoOutput(true);// 設置是否從httpUrlConnection讀入,默認情況下是true; httpConn.setDoInput(true);// 設定請求的方法為"POST",默認是GET httpConn.setRequestMethod("POST");// Post 請求不能使用緩存 httpConn.setUseCaches(false);//進行跳轉httpConn.setInstanceFollowRedirects(true);httpConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded; charset=" + sendCharset);if(reqHead!=null&&reqHead.size()>0){Iterator iterator =reqHead.keySet().iterator();while (iterator.hasNext()) {String key = (String) iterator.next();String val = (String)reqHead.get(key);httpConn.setRequestProperty(key,val);}}// 設定傳送的內容類型是可序列化的java對象 // (如果不設此項,在傳送序列化對象時,當WEB服務默認的不是這種類型時可能拋java.io.EOFException) httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); 
//            連接主機的超時時間(單位:毫秒)httpConn.setConnectTimeout(1000 * connectTimeout);
//            從主機讀取數據的超時時間(單位:毫秒) httpConn.setReadTimeout(1000 * readTimeout);// 連接,從postUrl.openConnection()至此的配置必須要在 connect之前完成,// 要注意的是connection.getOutputStream會隱含的進行 connect。
            httpConn.connect();DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());out.write(requestBody.getBytes(sendCharset));out.flush();out.close();int status = httpConn.getResponseCode();setStatus(status);if (status != HttpURLConnection.HTTP_OK) {System.out.print("發送請求失敗,狀態碼:[" + status + "] 返回信息:"+ httpConn.getResponseMessage());return null;}BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), readCharset));StringBuffer responseSb = new StringBuffer();String line = null;while ((line = reader.readLine()) != null) {responseSb.append(line.trim());}reader.close();return responseSb.toString().trim();} finally {httpConn.disconnect();}}public static void main(String[] args) {}}
package com.founder.ec.web.util.payments.tenpay;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
public class HttpClientUtil {public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 獲取不帶查詢串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 獲取查詢串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查詢字符串轉換成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把鍵值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader轉換成String<br/>* 注意:流關閉需要自行處理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 處理輸出<br/>* 注意:流關閉需要自行處理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len) throws IOException {int dataLen = data.length;int off = 0;while(off < dataLen) {if(len >= dataLen) {out.write(data, off, dataLen);} else {out.write(data, off, len);}//刷新緩沖區
            out.flush();off += len;dataLen -= len;}}/*** 獲取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 獲取CA證書信息* @param cafile CA證書文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串轉換成char數組* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存儲ca證書成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore
        ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());}
}
package com.founder.ec.common.utils;import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;public class HttpClientUtil {private static final Log logger = LogFactory.getLog(HttpClientUtil.class);public static byte[] doHttpClient(String url) {HttpClient c = new HttpClient();GetMethod getMethod = new GetMethod(url);try {getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,5000);getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());int statusCode = c.executeMethod(getMethod);if (statusCode != HttpStatus.SC_OK) {logger.error("doHttpClient Method failed: "+ getMethod.getStatusLine());}else{return getMethod.getResponseBody();}} catch (Exception e) {logger.error("doHttpClient errot : "+e.getMessage());} finally {getMethod.releaseConnection();}return null;}//財付通public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 獲取不帶查詢串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 獲取查詢串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查詢字符串轉換成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把鍵值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader轉換成String<br/>* 注意:流關閉需要自行處理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 處理輸出<br/>* 注意:流關閉需要自行處理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len) throws IOException {int dataLen = data.length;int off = 0;while(off < dataLen) {if(len >= dataLen) {out.write(data, off, dataLen);} else {out.write(data, off, len);}//刷新緩沖區
            out.flush();off += len;dataLen -= len;}}/*** 獲取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 獲取CA證書信息* @param cafile CA證書文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串轉換成char數組* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存儲ca證書成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore
        ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());}
}
package com.j1.website.util;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Set;import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;public class HttpClientUtil {/*** 發送HTTP請求* * @param url 接口地址* @param propsMap*            發送的參數*/public static String httpSend(String url, Map<String, Object> propsMap) {String responseMsg = "";HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);// POST請求// 參數設置Set<String> keySet = propsMap.keySet();NameValuePair[] postData = new NameValuePair[keySet.size()];int index = 0;for (String key : keySet) {postData[index++] = new NameValuePair(key, propsMap.get(key).toString());}postMethod.addParameters(postData);try {httpClient.executeMethod(postMethod);// 發送請求// 讀取內容BufferedReader reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));// byte[] responseBody = postMethod.getResponseBody();// 處理返回的內容// responseMsg = new String(responseBody);StringBuffer stringBuffer = new StringBuffer();String str;while ((str = reader.readLine()) != null) {stringBuffer.append(str);}responseMsg = stringBuffer.toString();} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {postMethod.releaseConnection();// 關閉連接
        }return responseMsg;}
}
package com.founder.ec.web.util.payments.weixin;import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
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.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.util.HashMap;
import java.util.Map;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;/*** Http客戶端工具類<br/>* 這是內部調用類,請不要在外部調用。* @author miklchen**/
public class HttpClientUtil {public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 獲取不帶查詢串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 獲取查詢串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查詢字符串轉換成Map<br/>* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把鍵值添加至Map<br/>* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader轉換成String<br/>* 注意:流關閉需要自行處理* @param reader* @return String* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 處理輸出<br/>* 注意:流關閉需要自行處理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len)throws IOException {int dataLen = data.length;int off = 0;while (off < data.length) {if (len >= dataLen) {out.write(data, off, dataLen);off += dataLen;} else {out.write(data, off, len);off += len;dataLen -= len;}// 刷新緩沖區
            out.flush();}}/*** 獲取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 獲取CA證書信息* @param cafile CA證書文件* @return Certificate* @throws CertificateException* @throws IOException*/public static Certificate getCertificate(File cafile)throws CertificateException, IOException {CertificateFactory cf = CertificateFactory.getInstance("X.509");FileInputStream in = new FileInputStream(cafile);Certificate cert = cf.generateCertificate(in);in.close();return cert;}/*** 字符串轉換成char數組* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}/*** 存儲ca證書成JKS格式* @param cert* @param alias* @param password* @param out* @throws KeyStoreException* @throws NoSuchAlgorithmException* @throws CertificateException* @throws IOException*/public static void storeCACert(Certificate cert, String alias,String password, OutputStream out) throws KeyStoreException,NoSuchAlgorithmException, CertificateException, IOException {KeyStore ks = KeyStore.getInstance("JKS");ks.load(null, null);ks.setCertificateEntry(alias, cert);// store keystore
        ks.store(out, HttpClientUtil.str2CharArray(password));}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());}/*** InputStream轉換成Byte* 注意:流關閉需要自行處理* @param in* @return byte* @throws Exception*/public static byte[] InputStreamTOByte(InputStream in) throws IOException{  int BUFFER_SIZE = 4096;  ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE];  int count = -1;  while((count = in.read(data,0,BUFFER_SIZE)) != -1)  outStream.write(data, 0, count);  data = null;  byte[] outByte = outStream.toByteArray();outStream.close();return outByte;  } /*** InputStream轉換成String* 注意:流關閉需要自行處理* @param in* @param encoding 編碼* @return String* @throws Exception*/public static String InputStreamTOString(InputStream in,String encoding) throws IOException{  return new String(InputStreamTOByte(in),encoding);}/*** 微信退款http請求* * @param certFilePath* @param password* @param orderRefundUrl* @param packageXml* @return* @throws Exception*/public static String refund4WxHttpClient(String certFilePath, String password, String orderRefundUrl, StringBuffer packageXml) throws Exception{StringBuffer retXmlContent = new StringBuffer();//獲取商戶證書KeyStore keyStore  = KeyStore.getInstance("PKCS12");FileInputStream instream = new FileInputStream(new File(certFilePath));try {keyStore.load(instream, password.toCharArray());} finally {instream.close();}// Trust own CA and all self-signed certsSSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray()).build();// Allow TLSv1 protocol onlySSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();try {HttpPost httppost = new HttpPost(orderRefundUrl);StringEntity myEntity = new StringEntity(packageXml.toString(), "UTF-8");  httppost.setEntity(myEntity);CloseableHttpResponse response = httpclient.execute(httppost);try {HttpEntity entity = response.getEntity();if (entity != null) {BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8"));String text;while ((text = bufferedReader.readLine()) != null) {retXmlContent.append(text);}}
//                EntityUtils.consume(entity);} finally {response.close();}} finally {httpclient.close();}return retXmlContent.toString();}
}
package com.founder.ec.web.util.payments.weixin.client;import com.founder.ec.web.util.payments.weixin.HttpClientUtil;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;/*** 財付通http或者https網絡通信客戶端<br/>* ========================================================================<br/>* api說明:<br/>* setReqContent($reqContent),設置請求內容,無論post和get,都用get方式提供<br/>* getResContent(), 獲取應答內容<br/>* setMethod(method),設置請求方法,post或者get<br/>* getErrInfo(),獲取錯誤信息<br/>* setCertInfo(certFile, certPasswd),設置證書,雙向https時需要使用<br/>* setCaInfo(caFile), 設置CA,格式未pem,不設置則不檢查<br/>* setTimeOut(timeOut), 設置超時時間,單位秒<br/>* getResponseCode(), 取返回的http狀態碼<br/>* call(),真正調用接口<br/>* getCharset()/setCharset(),字符集編碼<br/>* * ========================================================================<br/>**/
public class TenpayHttpClient {private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";private static final String JKS_CA_FILENAME = "tenpay_cacert.jks";private static final String JKS_CA_ALIAS = "tenpay";private static final String JKS_CA_PASSWORD = "1222075301";/** ca證書文件 */private File caFile;/** 證書文件 */private File certFile;/** 證書密碼 */private String certPasswd;/** 請求內容,無論post和get,都用get方式提供 */private String reqContent;/** 應答內容 */private String resContent;/** 請求方法 */private String method;/** 錯誤信息 */private String errInfo;/** 超時時間,以秒為單位 */private int timeOut;/** http應答編碼 */private int responseCode;/** 字符編碼 */private String charset;private InputStream inputStream;public TenpayHttpClient() {this.caFile = null;this.certFile = null;this.certPasswd = "";this.reqContent = "";this.resContent = "";this.method = "POST";this.errInfo = "";this.timeOut = 30;//30秒this.responseCode = 0;this.charset = "GBK";this.inputStream = null;}/*** 設置證書信息* @param certFile 證書文件* @param certPasswd 證書密碼*/public void setCertInfo(File certFile, String certPasswd) {this.certFile = certFile;this.certPasswd = certPasswd;}/*** 設置ca* @param caFile*/public void setCaInfo(File caFile) {this.caFile = caFile;}/*** 設置請求內容* @param reqContent 表求內容*/public void setReqContent(String reqContent) {this.reqContent = reqContent;}/*** 獲取結果內容* @return String* @throws IOException */public String getResContent() {try {this.doResponse();} catch (IOException e) {this.errInfo = e.getMessage();//return "";
        }return this.resContent;}/*** 設置請求方法post或者get* @param method 請求方法post/get*/public void setMethod(String method) {this.method = method;}/*** 獲取錯誤信息* @return String*/public String getErrInfo() {return this.errInfo;}/*** 設置超時時間,以秒為單位* @param timeOut 超時時間,以秒為單位*/public void setTimeOut(int timeOut) {this.timeOut = timeOut;}/*** 獲取http狀態碼* @return int*/public int getResponseCode() {return this.responseCode;}/*** 執行http調用。true:成功 false:失敗* @return boolean*/public boolean call() {boolean isRet = false;//httpif(null == this.caFile && null == this.certFile) {try {this.callHttp();isRet = true;} catch (IOException e) {this.errInfo = e.getMessage();}return isRet;}//httpstry {this.callHttps();isRet = true;} catch (UnrecoverableKeyException e) {this.errInfo = e.getMessage();} catch (KeyManagementException e) {this.errInfo = e.getMessage();} catch (CertificateException e) {this.errInfo = e.getMessage();} catch (KeyStoreException e) {this.errInfo = e.getMessage();} catch (NoSuchAlgorithmException e) {this.errInfo = e.getMessage();} catch (IOException e) {this.errInfo = e.getMessage();}return isRet;}protected void callHttp() throws IOException {if("POST".equals(this.method.toUpperCase())) {String url = HttpClientUtil.getURL(this.reqContent);String queryString = HttpClientUtil.getQueryString(this.reqContent);byte[] postData = queryString.getBytes(this.charset);this.httpPostMethod(url, postData);return ;}this.httpGetMethod(this.reqContent);} protected void callHttps() throws IOException, CertificateException,KeyStoreException, NoSuchAlgorithmException,UnrecoverableKeyException, KeyManagementException {// ca目錄String caPath = this.caFile.getParent();File jksCAFile = new File(caPath + "/"+ TenpayHttpClient.JKS_CA_FILENAME);if (!jksCAFile.isFile()) {X509Certificate cert = (X509Certificate) HttpClientUtil.getCertificate(this.caFile);FileOutputStream out = new FileOutputStream(jksCAFile);// store jks file
            HttpClientUtil.storeCACert(cert, TenpayHttpClient.JKS_CA_ALIAS,TenpayHttpClient.JKS_CA_PASSWORD, out);out.close();}FileInputStream trustStream = new FileInputStream(jksCAFile);FileInputStream keyStream = new FileInputStream(this.certFile);SSLContext sslContext = HttpClientUtil.getSSLContext(trustStream,TenpayHttpClient.JKS_CA_PASSWORD, keyStream, this.certPasswd);//關閉流
        keyStream.close();trustStream.close();if("POST".equals(this.method.toUpperCase())) {String url = HttpClientUtil.getURL(this.reqContent);String queryString = HttpClientUtil.getQueryString(this.reqContent);byte[] postData = queryString.getBytes(this.charset);this.httpsPostMethod(url, postData, sslContext);return ;}this.httpsGetMethod(this.reqContent, sslContext);}public boolean callHttpPost(String url, String postdata) {boolean flag = false;byte[] postData;try {postData = postdata.getBytes(this.charset);this.httpPostMethod(url, postData);flag = true;} catch (IOException e1) {e1.printStackTrace();}return flag;}/*** 以http post方式通信* @param url* @param postData* @throws IOException*/protected void httpPostMethod(String url, byte[] postData)throws IOException {HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);this.doPost(conn, postData);}/*** 以http get方式通信* * @param url* @throws IOException*/protected void httpGetMethod(String url) throws IOException {HttpURLConnection httpConnection =HttpClientUtil.getHttpURLConnection(url);this.setHttpRequest(httpConnection);httpConnection.setRequestMethod("GET");this.responseCode = httpConnection.getResponseCode();this.inputStream = httpConnection.getInputStream();}/*** 以https get方式通信* @param url* @param sslContext* @throws IOException*/protected void httpsGetMethod(String url, SSLContext sslContext)throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doGet(conn);}protected void httpsPostMethod(String url, byte[] postData,SSLContext sslContext) throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doPost(conn, postData);}/*** 設置http請求默認屬性* @param httpConnection*/protected void setHttpRequest(HttpURLConnection httpConnection) {//設置連接超時時間httpConnection.setConnectTimeout(this.timeOut * 1000);//User-AgenthttpConnection.setRequestProperty("User-Agent", TenpayHttpClient.USER_AGENT_VALUE);//不使用緩存httpConnection.setUseCaches(false);//允許輸入輸出httpConnection.setDoInput(true);httpConnection.setDoOutput(true);}/*** 處理應答* @throws IOException*/protected void doResponse() throws IOException {if(null == this.inputStream) {return;}//獲取應答內容this.resContent=HttpClientUtil.InputStreamTOString(this.inputStream,this.charset); //關閉輸入流this.inputStream.close();}/*** post方式處理* @param conn* @param postData* @throws IOException*/protected void doPost(HttpURLConnection conn, byte[] postData)throws IOException {// 以post方式通信conn.setRequestMethod("POST");// 設置請求默認屬性this.setHttpRequest(conn);// Content-Typeconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());final int len = 1024; // 1KB
        HttpClientUtil.doOutput(out, postData, len);// 關閉流
        out.close();// 獲取響應返回狀態碼this.responseCode = conn.getResponseCode();// 獲取應答輸入流this.inputStream = conn.getInputStream();}/*** get方式處理* @param conn* @throws IOException*/protected void doGet(HttpURLConnection conn) throws IOException {//以GET方式通信conn.setRequestMethod("GET");//設置請求默認屬性this.setHttpRequest(conn);//獲取響應返回狀態碼this.responseCode = conn.getResponseCode();//獲取應答輸入流this.inputStream = conn.getInputStream();}}

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279912.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279912.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279912.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

微軟公布Entity Framework 8.0規劃

微軟.NET團隊在博客上公布了有關 Entity Framework Core 8.0&#xff08;也稱為 EF Core 8 或 EF8&#xff09;的未來規劃。EF Core 8 是 EF Core 7 之后的下一個版本&#xff0c;這將是一個長期支持版本&#xff1b;計劃于 2023 年 11 月與 .NET 8 同時發布。該公司表示&#…

roku能不能安裝軟件_如何阻止假期更改Roku主題

roku能不能安裝軟件Wondering why your Roku looks…different? Roku occasionally changes the background for its millions of users, something they call a “featured theme.” 想知道為什么您的Roku看起來...不同嗎&#xff1f; Roku偶爾會改變其數百萬用戶的背景&…

助力AIoT,雅觀科技發布空間智能化操作系統

雷鋒網(公眾號&#xff1a;雷鋒網)消息&#xff0c;3月14日&#xff0c;雅觀科技在上海舉辦了“「AI」悟及物 「柔」生萬屋”2019雅觀科技新品發布會&#xff0c;發布了空間智能化操作系統Akeeta、空間智能化柔性服務技術中臺Matrix&#xff0c;以及基于兩者開發的雅觀智慧社區…

HTTP與HTTPS區別(詳細)

轉&#xff1a;http://blog.sina.com.cn/s/blog_6eb3177a0102x66r.html 1、減少http請求&#xff08;合并文件、合并圖片&#xff09;2、優化圖片文件&#xff0c;減小其尺寸&#xff0c;特別是縮略圖&#xff0c;一定要按尺寸生成縮略圖然后調用&#xff0c;不要在網頁中用res…

Ajenti-Linux控制面板之自動化運維工具

ajenti http://ajenti.org/ https://github.com/ajenti/ajenti 源碼 http://docs.ajenti.org/en/latest/ http://docs.ajenti.org/en/latest/man/install.html# 安裝部署Fast remote access for every occasion Install once and never google for PuTTY downloads again. An…

MongoDB C# Driver 快速入門

MongoDB的官方C#驅動可以通過這個鏈接得到。鏈接提供了.msi和.zip兩種方式獲取驅動dll文件。C#驅動的基本數據庫連接&#xff0c;增刪改查操作。在使用C#驅動的時候&#xff0c;要在工程中添加"MongoDB.Bson.dll"和"MongoDB.Driver.dll"的引用。同時要在代…

如何在Windows 10的地圖應用程序中獲取離線地圖

If you know you’re going to be using your PC in a location without an Internet connection, and you need access to maps, you can download maps for specific areas in the “Maps” app in Windows 10 and use them offline. 如果您知道要在沒有Internet連接的地方使…

Hive初識(二)

Hive分區Hive組織表到分區。它是將一個表到基于分區列&#xff0c;如日期&#xff0c;城市和部門的值相關方式。使用分區&#xff0c;很容易對數據進行部分查詢。表或分區是細分成桶&#xff0c;以提供額外的結構&#xff0c;可以使用更高效的查詢的數據。桶的工作是基于表的一…

網站計數器 web映射

站點的網站計數器的操作 <% page import"java.math.BigInteger" %> <% page import"java.io.File" %> <% page import"java.util.Scanner" %> <% page import"java.io.FileInputStream" %> <% page import…

XenApp_XenDesktop_7.6實戰篇之八:申請及導入許可證

1. 申請許可證 Citrix XenApp_XenDesktop7.6和XenServer 6.5申請許可證的步驟是一致的&#xff0c;由于之前我已經申請過XenApp_XenDesktop的許可證&#xff0c;本次以XenServer6.5的許可證申請為例。 1.1 在申請試用或購買Citrix產品時&#xff0c;收到相應的郵件&#xff0…

Windows 11的記事本將獲得類似瀏覽器的標簽功能

Windows 11已經向全世界的客戶推出&#xff0c;自從它問世以來已經收到各種有趣的更新。例如&#xff0c;Windows 11的22H2版本&#xff08;操作系統的第一個大更新&#xff09;為文件資源管理器添加了標簽&#xff0c;啟用了任務欄的拖放支持&#xff0c;以及更多。Windows-11…

C#種將String類型轉換成int型

API&#xff1a; 有一點是需要注意的&#xff0c;那就是必須保證該String類型內全為數字&#xff0c;能確保轉換正確&#xff1b; 1.int.Parse(str);2.TryParse(str, out intA);3. Convert.ToInt32(str);以上都可以&#xff0c;其中 1和3 需要try&#xff5b;&#xff5d;異常&…

【本人禿頂程序員】技巧分享丨spring的RestTemplate的妙用,你知道嗎?

←←←←←←←←←←←← 快&#xff01;點關注 為什么要使用RestTemplate&#xff1f; 隨著微服務的廣泛使用&#xff0c;在實際的開發中&#xff0c;客戶端代碼中調用RESTful接口也越來越常見。在系統的遺留代碼中&#xff0c;你可能會看見有一些代碼是使用HttpURLConnectio…

譯?:Top Three Use Cases for Dapr and Kubernetes

有關譯者&#xff1a;陳東海(seachen)&#xff0c;?前就職于騰訊&#xff0c;同時在社區也是?名Dapr Member.導語&#xff1a;在SDLC(Software Development Lifecycle軟件開發?命周期中)&#xff0c;絕?多數CNCF項?都是專注于軟件開發的中后期階段&#xff0c;特別是運維和…

MySQL數據庫的datetime與timestamp

MySQL數據庫中有datetime與timestamp兩種日期時間型數據類型&#xff0c;其中timestamp可以用timestamp(n)來表示年月日時分秒的取值精度&#xff0c;如果n14則完整匹配于datetime的精度&#xff0c;那為什么還需要datetime這種類型呢&#xff1f;我做過試驗&#xff0c;timest…

平視相機svo開源項目_什么是平視顯示器(HUD),我應該得到一個嗎?

平視相機svo開源項目In a world full of augmented reality snowboard goggles and Google Glass, it seems only fair that our cars get to enjoy some of the same treatment. Heads-up displays, or “HUDs” as they’re better known, are a new type of add-on for cons…

yum 下載RPM包而不進行安裝

yum命令本身就可以用來下載一個RPM包&#xff0c;標準的yum命令提供了--downloadonly(只下載)的選項來達到這個目的。 $ sudo yum install --downloadonly <package-name> 默認情況下&#xff0c;一個下載的RPM包會保存在下面的目錄中: /var/cache/yum/x86_64/[centos/fe…

react項目打包后路徑找不到,項目打開后頁面空白的問題

使用 npm install -g create-react-app快速生成項目腳手架打包后出現資源找不到的路徑問題&#xff1a; 解決辦法&#xff1a;在package.json設置homepage 轉載于:https://www.cnblogs.com/lan-cheng/p/10541606.html

linux 下實現ssh免密鑰登錄

小伙伴經常在運維的時候需要ssh到很多其他的服務器&#xff0c;但是又要每次輸入密碼&#xff0c;一兩臺還沒什么&#xff0c;多了就煩了。所以這里教大家如何直接ssh到其他機器而不用輸入密碼。[rootjw ~]# ssh-keygen -t rsaGenerating public/private rsa key pair.Enter fi…