我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Java如何使用HTTPclient访问url获得数据

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

Java如何使用HTTPclient访问url获得数据

使用HTTPclient访问url获得数据

最近项目上有个小功能需要调用第三方的http接口取数据,用到了HTTPclient,算是做个笔记吧!

1、使用get方法取得数据


  
public static String getGetDateByUrl(String url){  
    String data = null;  
    //构造HttpClient的实例    
    HttpClient httpClient = new HttpClient();    
    //创建GET方法的实例    
    GetMethod getMethod = new GetMethod(url);   
    //设置头信息:如果不设置User-Agent可能会报405,导致取不到数据  
    getMethod.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:39.0) Gecko/20100101 Firefox/39.0");  
    //使用系统提供的默认的恢复策略    
    getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());    
    try{  
        //开始执行getMethod    
        int statusCode = httpClient.executeMethod(getMethod);  
        if (statusCode != HttpStatus.SC_OK) {  
            System.err.println("Method failed:" + getMethod.getStatusLine());  
        }  
        //读取内容  
        byte[] responseBody = getMethod.getResponseBody();  
        //处理内容  
        data = new String(responseBody);  
    }catch (HttpException e){  
        //发生异常,可能是协议不对或者返回的内容有问题  
        System.out.println("Please check your provided http address!");  
        data = "";  
        e.printStackTrace();  
    }catch(IOException e){  
        //发生网络异常  
        data = "";  
        e.printStackTrace();  
    }finally{  
        //释放连接  
        getMethod.releaseConnection();  
    }  
    return data;  
}  

2、使用POST方法取得数据


  
public static String getPostDateByUrl(String url,Map<String ,String> array){  
    String data = null;  
    //构造HttpClient的实例    
    HttpClient httpClient = new HttpClient();    
    //创建post方法的实例    
    PostMethod postMethod = new PostMethod(url);   
    //设置头信息  
    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");  
    //遍历设置要提交的参数  
    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);  
    }  
    //使用系统提供的默认的恢复策略    
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());    
    try{  
        //执行postMethod    
        int statusCode = httpClient.executeMethod(postMethod);  
        if (statusCode != HttpStatus.SC_OK) {  
            System.err.println("Method failed:" + postMethod.getStatusLine());  
        }  
        //读取内容  
        byte[] responseBody = postMethod.getResponseBody();  
        //处理内容  
        data = new String(responseBody);  
    }catch (HttpException e){  
        //发生致命的异常,可能是协议不对或者返回的内容有问题  
        System.out.println("Please check your provided http address!");  
        data = "";  
        e.printStackTrace();  
    }catch(IOException e){  
        //发生网络异常  
        data = "";  
        e.printStackTrace();  
    }finally{  
        //释放连接  
        postMethod.releaseConnection();  
    }  
    System.out.println(data);  
    return data;  
}  

使用httpclient后台调用url方式

使用httpclient调用后台的时候接收url类型的参数需要使用UrlDecoder解码,调用的时候需要对参数使用UrlEncoder对参数进行编码,然后调用。


@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";
	}
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Java如何使用HTTPclient访问url获得数据

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

php中如何获取访问类的数据呢

这篇文章将为大家详细讲解有关php中如何获取访问类的数据呢,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。self是一种静态绑定,换言之就是当类进行编译的时候self已经明确绑定了类名,因此不论多少继承,也
2023-06-13

getSQLinfo.vbs如何获得SQL数据/日志空间使用情况

这篇文章给大家分享的是有关getSQLinfo.vbs如何获得SQL数据/日志空间使用情况的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。获得SQL数据/日志空间使用,已使用的和未使用的空间的脚本 getSQLin
2023-06-08

如何使用Java获取Json中的数据

这篇文章主要介绍“如何使用Java获取Json中的数据”,在日常操作中,相信很多人在如何使用Java获取Json中的数据问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”如何使用Java获取Json中的数据”的疑
2023-07-06

Java如何使用访问修饰符

这篇文章主要介绍Java如何使用访问修饰符,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!1、简介访问修饰符是Java语法中很基础的一部分,但是能正确的使用Java访问修饰符的程序员只在少数。在Java组件开发中,如果
2023-06-25

SpringBoot如何使用JdbcTemplate访问操作数据库

这篇文章给大家分享的是有关SpringBoot如何使用JdbcTemplate访问操作数据库的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。Spring对数据库的操作在jdbc上s面做了深层次的封装,使用sprin
2023-06-29

如何使用原生JS获取URL链接参数

这篇文章将为大家详细讲解有关如何使用原生JS获取URL链接参数,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1. 获取方式总结利用原生JS获取URL链接参数的方法也有好几种,今天我们依次来讲解常见的几种:
2023-06-29

如何使用本机访问阿里云数据库

阿里云数据库是一个强大、可靠的云数据库服务,它能够帮助企业和个人轻松地管理和使用数据。然而,有些用户可能想要使用本机访问阿里云数据库,以便更好地控制和管理他们的数据。本篇文章将详细介绍如何使用本机访问阿里云数据库。如何使用本机访问阿里云数据库:创建阿里云数据库实例首先,你需要在阿里云上创建一个数据库实例。你可以在
如何使用本机访问阿里云数据库
2023-12-09

如何创建使用VB.NET线程访问数据库

这篇文章将为大家详细讲解有关如何创建使用VB.NET线程访问数据库,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。创建VB.NET线程访问数据库数据库应用中,特别是网络数据库访问,因为可能要访问的数据量较大
2023-06-17

Spring Boot使用MyBatis如何实现访问数据库

今天就跟大家聊聊有关Spring Boot使用MyBatis如何实现访问数据库,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。基于spring boot开发的微服务应用,与MyBati
2023-05-31

Java解析DICOM图之如何获得16进制数据详解

前言在最近的一个项目需要用JAVA来解析DICOM图片,DICOM被广泛应用于放射医疗,心血管成像以及放射诊疗诊断设备(X射线,CT,核磁共振,超声等),并且在眼科和牙科等其它医学领域得到越来越深入广泛的应用,在实现中遇到一些问题下面做一些
2023-05-31

如何使用阿里云数据库访问外网

随着互联网技术的发展,数据已经成为企业的重要资产,对于数据库的访问也成为企业日常操作的一部分。而阿里云数据库作为一种强大的数据库服务,其访问外网的功能更是受到许多企业的青睐。然而,许多用户可能会遇到阿里云数据库无法访问外网的问题。这篇文章将详细介绍如何使用阿里云数据库访问外网,希望能帮助到需要的用户。一、设置数据
如何使用阿里云数据库访问外网
2023-11-08

如何使用 go 访问和修改备用数据流(ADS)

学习Golang要努力,但是不要急!今天的这篇文章《如何使用 go 访问和修改备用数据流(ADS)》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!问题内容如何使用 golan
如何使用 go 访问和修改备用数据流(ADS)
2024-04-04

如何使用Spring Data repository进行数据层的访问

本篇内容主要讲解“如何使用Spring Data repository进行数据层的访问”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何使用Spring Data repository进行数据层
2023-07-02

如何使用Python缓存提高数据访问速度

这篇文章主要讲解了“如何使用Python缓存提高数据访问速度”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何使用Python缓存提高数据访问速度”吧!Python使用缓存在开发Web应用或
2023-07-06

Linq如何调用数据访问服务

小编给大家分享一下Linq如何调用数据访问服务,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!Linq调用数据访问服务Linq调用数据访问服务来进行留言、回复、删除
2023-06-17

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录