亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Java如何使用HTTPclient訪問url獲得數(shù)據(jù)

 更新時(shí)間:2021年09月17日 12:00:04   作者:quainter  
這篇文章主要介紹了Java使用HTTPclient訪問url獲得數(shù)據(jù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

使用HTTPclient訪問url獲得數(shù)據(jù)

最近項(xiàng)目上有個(gè)小功能需要調(diào)用第三方的http接口取數(shù)據(jù),用到了HTTPclient,算是做個(gè)筆記吧!

1、使用get方法取得數(shù)據(jù)

/** 
 * 根據(jù)URL試用get方法取得返回的數(shù)據(jù) 
 * @param url 
 *        URL地址,參數(shù)直接掛在URL后面即可 
 * @return 
 */  
public static String getGetDateByUrl(String url){  
    String data = null;  
    //構(gòu)造HttpClient的實(shí)例    
    HttpClient httpClient = new HttpClient();    
    //創(chuàng)建GET方法的實(shí)例    
    GetMethod getMethod = new GetMethod(url);   
    //設(shè)置頭信息:如果不設(shè)置User-Agent可能會(huì)報(bào)405,導(dǎo)致取不到數(shù)據(jù)  
    getMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:39.0) Gecko/20100101 Firefox/39.0");  
    //使用系統(tǒng)提供的默認(rèn)的恢復(fù)策略    
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());    
    try{  
        //開始執(zhí)行g(shù)etMethod    
        int statusCode = httpClient.executeMethod(getMethod);  
        if (statusCode != HttpStatus.SC_OK) {  
            System.err.println("Method failed:" + getMethod.getStatusLine());  
        }  
        //讀取內(nèi)容  
        byte[] responseBody = getMethod.getResponseBody();  
        //處理內(nèi)容  
        data = new String(responseBody);  
    }catch (HttpException e){  
        //發(fā)生異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題  
        System.out.println("Please check your provided http address!");  
        data = "";  
        e.printStackTrace();  
    }catch(IOException e){  
        //發(fā)生網(wǎng)絡(luò)異常  
        data = "";  
        e.printStackTrace();  
    }finally{  
        //釋放連接  
        getMethod.releaseConnection();  
    }  
    return data;  
}  

2、使用POST方法取得數(shù)據(jù)

/** 
 * 根據(jù)post方法取得返回?cái)?shù)據(jù) 
 * @param url 
 *          URL地址 
 * @param array 
 *          需要以post形式提交的參數(shù) 
 * @return 
 */  
public static String getPostDateByUrl(String url,Map<String ,String> array){  
    String data = null;  
    //構(gòu)造HttpClient的實(shí)例    
    HttpClient httpClient = new HttpClient();    
    //創(chuàng)建post方法的實(shí)例    
    PostMethod postMethod = new PostMethod(url);   
    //設(shè)置頭信息  
    postMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:39.0) Gecko/20100101 Firefox/39.0");  
    postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");  
    //遍歷設(shè)置要提交的參數(shù)  
    Iterator it = array.entrySet().iterator();    
    while (it.hasNext()){  
        Map.Entry<String,String> entry =(Map.Entry) it.next();    
        String key = entry.getKey();    
        String value = entry.getValue().trim();    
        postMethod.setParameter(key,value);  
    }  
    //使用系統(tǒng)提供的默認(rèn)的恢復(fù)策略    
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());    
    try{  
        //執(zhí)行postMethod    
        int statusCode = httpClient.executeMethod(postMethod);  
        if (statusCode != HttpStatus.SC_OK) {  
            System.err.println("Method failed:" + postMethod.getStatusLine());  
        }  
        //讀取內(nèi)容  
        byte[] responseBody = postMethod.getResponseBody();  
        //處理內(nèi)容  
        data = new String(responseBody);  
    }catch (HttpException e){  
        //發(fā)生致命的異常,可能是協(xié)議不對(duì)或者返回的內(nèi)容有問題  
        System.out.println("Please check your provided http address!");  
        data = "";  
        e.printStackTrace();  
    }catch(IOException e){  
        //發(fā)生網(wǎng)絡(luò)異常  
        data = "";  
        e.printStackTrace();  
    }finally{  
        //釋放連接  
        postMethod.releaseConnection();  
    }  
    System.out.println(data);  
    return data;  
}  

使用httpclient后臺(tái)調(diào)用url方式

使用httpclient調(diào)用后臺(tái)的時(shí)候接收url類型的參數(shù)需要使用UrlDecoder解碼,調(diào)用的時(shí)候需要對(duì)參數(shù)使用UrlEncoder對(duì)參數(shù)進(jìn)行編碼,然后調(diào)用。

@SuppressWarnings("deprecation")
	@RequestMapping(value = "/wechatSigns", produces = "application/json;charset=utf-8")
	@ResponseBody
	public String wechatSigns(HttpServletRequest request, String p6, String p13) {
		Map<String, String> ret = new HashMap<String, String>();
		try {
			System.out.println("*****************************************p6:"+p6);
			URLDecoder.decode(p13);
			System.out.println("*****************************************p13:"+p13);
			String p10 = "{\"p1\":\"1\",\"p2\":\"\",\"p6\":\"" + p6 + "\",\"p13\":\"" + p13 + "\"}";
			p10 = URLEncoder.encode(p10, "utf-8");
			String url = WebserviceUtil.getGetSignatureUrl() + "?p10=" + p10;
			String result = WebConnectionUtil.sendGetRequest(url);
			JSONObject fromObject = JSONObject.fromObject(URLDecoder.decode(result, "utf-8"));
			System.out.println(fromObject);
			String resultCode = JSONObject.fromObject(fromObject.getString("meta")).getString("result");
			if ("0".equals(resultCode)) {
				JSONObject fromObject2 = JSONObject.fromObject(fromObject.get("data"));
				String timestamp = fromObject2.getString("timestamp");
				String appId = fromObject2.getString("appId");
				String nonceStr = fromObject2.getString("nonceStr");
				String signature = fromObject2.getString("signature");
				ret.put("timestamp", timestamp);
				ret.put("appId", appId);
				ret.put("nonceStr", nonceStr);
				ret.put("signature", signature);
				JSONObject jo = JSONObject.fromObject(ret);
				return ResultJsonBean.success(jo.toString());
			} else {
				String resultMsg = JSONObject.fromObject(fromObject.getString("meta")).getString("errMsg");
				return ResultJsonBean.fail(ConnectOauthCodeInfo.REQ_WECHATTOCKEN_CODE, resultMsg, "");
			}
		} catch (Exception e) {
			logger.error(e, e);
			return ResultJsonBean.fail(ConnectOauthCodeInfo.REQ_WECHATREQERROE_CODE,
					ConnectOauthCodeInfo.REQ_WECHATREQERROE_CODE, "");
		}
	}
<pre name="code" class="java">package com.dcits.djk.core.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; 
import net.sf.json.JSONObject;
 
public class WebConnectionUtil {	
	public static String sendPostRequest(String url,Map paramMap,String userId){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;		
		try{
			httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			if(userId != null || "".equals(userId) ){
				formparams.add(new BasicNameValuePair("userId",userId));
			}
			Set keSet=paramMap.entrySet();
			for(Iterator itr=keSet.iterator();itr.hasNext();){
				Map.Entry me=(Map.Entry)itr.next();
				Object key=me.getKey();
				Object valueObj=me.getValue();
				String[] value=new String[1];
				if(valueObj == null){
					value[0] = "";
				}else{
					if(valueObj instanceof String[]){  
			            value=(String[])valueObj;  
			        }else{  
			            value[0]=valueObj.toString();  
			        }
				}
				for(int k=0;k<value.length;k++){  
					formparams.add(new BasicNameValuePair(key.toString(),StringUtil.filterSpecialChar(value[k])));
		        }
			}
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
 
			response = httpclient.execute(httppost);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
	
	public static String sendPostRequest(String url,Map paramMap){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;
		
		try{
			httpclient = HttpClients.createDefault();
			HttpPost httppost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			Set keSet=paramMap.entrySet();
			for(Iterator itr=keSet.iterator();itr.hasNext();){
				Map.Entry me=(Map.Entry)itr.next();
				Object key=me.getKey();
				Object valueObj=me.getValue();
				String[] value=new String[1];
				if(valueObj == null){
					value[0] = "";
				}else{
					if(valueObj instanceof String[]){  
			            value=(String[])valueObj;  
			        }else{  
			            value[0]=valueObj.toString();  
			        }
				}
				for(int k=0;k<value.length;k++){  
					formparams.add(new BasicNameValuePair(key.toString(),StringUtil.filterSpecialChar(value[k])));
		        }
			}
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity);
 
			response = httpclient.execute(httppost);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}	
	
	public static String downloadFileToImgService(String remoteUtl,String imgUrl,String tempUrl){
		CloseableHttpClient httpclientRemote=null;
		CloseableHttpResponse responseRemote=null;		
		CloseableHttpClient httpclientImg=null;
		CloseableHttpResponse responseImg=null;		
		try{
			httpclientRemote = HttpClients.createDefault();
			HttpGet httpgetRemote = new HttpGet(remoteUtl);
			
			responseRemote = httpclientRemote.execute(httpgetRemote);
			if(responseRemote.getStatusLine().getStatusCode() != 200){
				return "";
			}
			HttpEntity resEntityRemote = responseRemote.getEntity();
			InputStream isRemote = resEntityRemote.getContent();
			//寫入文件
			File file = null;
			
			boolean isDownSuccess = true;
			BufferedOutputStream bos = null;
			try{
				BufferedInputStream bif = new BufferedInputStream(isRemote);
				byte bf[] = new byte[28];
				bif.read(bf);
				String suffix = FileTypeUtil.getSuffix(bf);
				file = new File(tempUrl + "/" + UuidUtil.get32Uuid()+suffix);
				bos = new BufferedOutputStream(new FileOutputStream(file));
				if(!file.exists()){
					file.createNewFile();
				}
				bos.write(bf, 0, 28);
				byte b[] = new byte[1024*3];
				int len = 0;
				while((len=bif.read(b)) != -1){
					bos.write(b, 0, len);
				}
			}catch(Exception e){
				e.printStackTrace();
				isDownSuccess = false;
			}finally{
				try {
					if(bos != null){
						bos.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if(!isDownSuccess){
				return "";
			}
			
			httpclientImg = HttpClients.createDefault();
			HttpPost httpPostImg = new HttpPost(imgUrl);
			MultipartEntityBuilder requestEntity = MultipartEntityBuilder.create();
			requestEntity.addBinaryBody("userFile", file);
			
			HttpEntity httprequestImgEntity = requestEntity.build();
			httpPostImg.setEntity(httprequestImgEntity);
			responseImg = httpclientImg.execute(httpPostImg);
			if(responseImg.getStatusLine().getStatusCode() != 200){
				return "";
			}
			HttpEntity entity = responseImg.getEntity();
			String json = EntityUtils.toString(entity, "UTF-8");
			json = json.replaceAll("\"","");
			String[] jsonMap = json.split(",");
			String resultInfo = "";
			for(int i = 0;i < jsonMap.length;i++){
				String str = jsonMap[i];
				if(str.startsWith("url:")){
					resultInfo = str.substring(4);
				}else if(str.startsWith("{url:")){
					resultInfo = str.substring(5);
				}
			}
			if(resultInfo.endsWith("}")){
				resultInfo = resultInfo.substring(0,resultInfo.length()-1);
			}
			try{
				if(file != null){
					file.delete();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			return resultInfo;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclientRemote != null){
					httpclientRemote.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(responseRemote != null){
					responseRemote.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(httpclientImg != null){
					httpclientImg.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(responseImg != null){
					responseImg.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	public static String downloadFileToImgService(File file,String imgUrl){
		CloseableHttpClient httpclientImg=null;
		CloseableHttpResponse responseImg=null;		
		try{
			httpclientImg = HttpClients.createDefault();
			HttpPost httpPostImg = new HttpPost(imgUrl);
			MultipartEntityBuilder requestEntity = MultipartEntityBuilder.create();
			requestEntity.addBinaryBody("userFile", file);
			
			HttpEntity httprequestImgEntity = requestEntity.build();
			httpPostImg.setEntity(httprequestImgEntity);
			responseImg = httpclientImg.execute(httpPostImg);
			if(responseImg.getStatusLine().getStatusCode() != 200){
				return "";
			}
			HttpEntity entity = responseImg.getEntity();
			String json = EntityUtils.toString(entity, "UTF-8");
			json = json.replaceAll("\"","");
			String[] jsonMap = json.split(",");
			String resultInfo = "";
			for(int i = 0;i < jsonMap.length;i++){
				String str = jsonMap[i];
				if(str.startsWith("url:")){
					resultInfo = str.substring(4);
				}else if(str.startsWith("{url:")){
					resultInfo = str.substring(5);
				}
			}
			if(resultInfo.endsWith("}")){
				resultInfo = resultInfo.substring(0,resultInfo.length()-1);
			}
			return resultInfo;
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclientImg != null){
					httpclientImg.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(responseImg != null){
					responseImg.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}
	
	public static String sendGetRequest(String url){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;
		try{
			httpclient = HttpClients.createDefault();
			HttpGet httpGet = new HttpGet(url);
 
			response = httpclient.execute(httpGet);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
	
	public static String sendHttpsPostRequestUseStream(String url,String param){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;		
		try{
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			TrustManager[] tm = {xtm};
			ctx.init(null,tm,null);
			HostnameVerifier hv = new HostnameVerifier(){
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			};
			httpclient = HttpClients.custom().setSSLHostnameVerifier(hv).setSSLContext(ctx).build();
			HttpPost httpPost = new HttpPost(url);
			StringEntity strEntity = new StringEntity(param,"utf-8");
			httpPost.setEntity(strEntity);
			
 			response = httpclient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
	
	public static String sendHttpsPostRequestUseStream(String url,Map paramMap){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;		
		try{
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			TrustManager[] tm = {xtm};
			ctx.init(null,tm,null);
			HostnameVerifier hv = new HostnameVerifier(){
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			};
			httpclient = HttpClients.custom().setSSLHostnameVerifier(hv).setSSLContext(ctx).build();
			HttpPost httpPost = new HttpPost(url);
			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
			Set keSet=paramMap.entrySet();
			for(Iterator itr=keSet.iterator();itr.hasNext();){
				Map.Entry me=(Map.Entry)itr.next();
				Object key=me.getKey();
				Object valueObj=me.getValue();
				String[] value=new String[1];
				if(valueObj == null){
					value[0] = "";
				}else{
					if(valueObj instanceof String[]){  
			            value=(String[])valueObj;  
			        }else{  
			            value[0]=valueObj.toString();  
			        }
				}
				for(int k=0;k<value.length;k++){  
					formparams.add(new BasicNameValuePair(key.toString(),StringUtil.filterSpecialChar(value[k])));
		        }
			}
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httpPost.setEntity(uefEntity);
			
 			response = httpclient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
	
	public static String sendHttpsGetRequestUseStream(String url){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;		
		try{
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			TrustManager[] tm = {xtm};
			ctx.init(null,tm,null);
			HostnameVerifier hv = new HostnameVerifier(){
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			};
			httpclient = HttpClients.custom().setSSLHostnameVerifier(hv).setSSLContext(ctx).build();
			HttpGet httpGet = new HttpGet(url);
			
 			response = httpclient.execute(httpGet);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
	
	public static String sendHttpsPostRequestUseStreamForYZL(String url,OauthToken param){
		CloseableHttpClient httpclient=null;
		CloseableHttpResponse response=null;		
		try{
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager xtm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
					
				}
 
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			TrustManager[] tm = {xtm};
			ctx.init(null,tm,null);
			HostnameVerifier hv = new HostnameVerifier(){
				public boolean verify(String arg0, SSLSession arg1) {
					return true;
				}
			};
			httpclient = HttpClients.custom().setSSLHostnameVerifier(hv).setSSLContext(ctx).build();
			HttpPost httpPost = new HttpPost(url);
			StringEntity strEntity = new StringEntity(param.toString(),"utf-8");
			httpPost.setEntity(strEntity);
			httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
			
 			response = httpclient.execute(httpPost);
			if(response.getStatusLine().getStatusCode() == 200){
				HttpEntity entity = response.getEntity();
				String resultInfo = EntityUtils.toString(entity, "UTF-8");
				return resultInfo;
			}else{
				return response.getStatusLine().getStatusCode() + "";
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try {
				if(httpclient != null){
					httpclient.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if(response != null){
					response.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "404";
	}
}

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • springboot整合dubbo設(shè)置全局唯一ID進(jìn)行日志追蹤的示例代碼

    springboot整合dubbo設(shè)置全局唯一ID進(jìn)行日志追蹤的示例代碼

    這篇文章主要介紹了springboot整合dubbo設(shè)置全局唯一ID進(jìn)行日志追蹤,本文通過圖文示例相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-10-10
  • java 對(duì)象參數(shù)去空格方式代碼實(shí)例

    java 對(duì)象參數(shù)去空格方式代碼實(shí)例

    這篇文章主要介紹了java 對(duì)象參數(shù)去空格方式代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Java中的vector類使用示例小結(jié)

    Java中的vector類使用示例小結(jié)

    Vector與ArrayList的實(shí)現(xiàn)基本相似,同樣是基于動(dòng)態(tài)數(shù)組,同樣是需要擴(kuò)容,下面舉了三個(gè)簡(jiǎn)短的例子來幫助大家理解vertor:
    2016-05-05
  • java File類重要方法以及如何操作文件詳解

    java File類重要方法以及如何操作文件詳解

    這篇文章主要為大家介紹了java File類重要方法以及如何操作文件詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-06-06
  • Java設(shè)計(jì)模式編程中的責(zé)任鏈模式使用示例

    Java設(shè)計(jì)模式編程中的責(zé)任鏈模式使用示例

    這篇文章主要介紹了Java設(shè)計(jì)模式編程中的責(zé)任鏈模式使用示例,責(zé)任鏈模式可以避免很多請(qǐng)求的發(fā)送者和接收者之間的耦合關(guān)系,需要的朋友可以參考下
    2016-05-05
  • Spring如何通過注解引入外部資源(PropertySource?Value)

    Spring如何通過注解引入外部資源(PropertySource?Value)

    這篇文章主要為大家介紹了Spring通過注解@PropertySource和@Value引入外部資源的方法實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-07-07
  • 詳解springboot中junit回滾

    詳解springboot中junit回滾

    本篇文章主要介紹了springboot中junit回滾,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-10-10
  • Java SpringBoot自動(dòng)裝配原理詳解

    Java SpringBoot自動(dòng)裝配原理詳解

    這篇文章主要介紹了詳解Spring Boot自動(dòng)裝配的原理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-09-09
  • 淺談Java中@Autowired和@Inject注解的區(qū)別和使用場(chǎng)景

    淺談Java中@Autowired和@Inject注解的區(qū)別和使用場(chǎng)景

    本文主要介紹了淺談Java中@Autowired和@Inject注解的區(qū)別和使用場(chǎng)景,@Autowired注解在依賴查找方式和注入方式上更加靈活,適用于Spring框架中的依賴注入,而@Inject注解在依賴查找方式上更加嚴(yán)格,適用于Java的依賴注入標(biāo)準(zhǔn),感興趣的可以了解一下
    2023-11-11
  • Java實(shí)現(xiàn)文件分割和文件合并實(shí)例

    Java實(shí)現(xiàn)文件分割和文件合并實(shí)例

    本篇文章主要介紹了Java實(shí)現(xiàn)文件分割和文件合并實(shí)例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-08-08

最新評(píng)論