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

目录
  • 使用HTTPclient访问url获得数据
    • 1、使用get方法取得数据
    • 2、使用POST方法取得数据
  • 使用httpclient后台调用url方式

使用HTTPclient访问url获得数据

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

1、使用get方法取得数据

/**
 * 根据URL试用get方法取得返回的数据
 * @param url
 *        URL地址,参数直接挂在URL后面即可
 * @return
 */
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方法取得数据

/**
 * 根据post方法取得返回数据
 * @param url
 *          URL地址
 * @param array
 *          需要以post形式提交的参数
 * @return
 */
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";
	}
}

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

(0)

相关推荐

  • java发送url请求获取返回值的二种方法

    下面提供二种方法会使用java发送url请求,并获取服务器返回的值 第一种方法: 复制代码 代码如下: import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.HttpClient;import org.apache.http.client.entity.UrlEncodedFor

  • Java 使用 HttpClient 发送 GET请求和 POST请求

    目录 概述 认证方式 基础认证Auth 用户名密码认证 Bearer Token 认证 配置超时 生成 RequestConfig 设置超时时间 概述 日常工作中,我们经常会有发送 HTTP 网络请求的需求,概括下我们常见的发送 HTTP 请求的需求内容: 可以发送基本的 GET/POST/PUT/DELETE 等请求: HTTP请求,可以附带认证,包括基本的 用户名/密码 认证,以及 Bearer Token 认证: 请求可以自定义 超时时间: HTTP请求可以带参数,也可以不带参数: HTT

  • JAVA通过HttpClient发送HTTP请求的方法示例

    HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 嵌入在 HTML 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向URI,或者其它和 HTTP 运输无关的功能. HttpClient使用 使用需要引入jar包,maven项目引入如下: <dependency> <groupId>org.apache.htt

  • java发送HttpClient请求及接收请求结果过程的简单实例

    一. 1.写一个HttpRequestUtils工具类,包括post请求和get请求 package com.brainlong.framework.util.httpclient; import net.sf.json.JSONObject; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.HttpResponse; import org.apache.http.client.methods.Htt

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

    目录 使用HTTPclient访问url获得数据 1.使用get方法取得数据 2.使用POST方法取得数据 使用httpclient后台调用url方式 使用HTTPclient访问url获得数据 最近项目上有个小功能需要调用第三方的http接口取数据,用到了HTTPclient,算是做个笔记吧! 1.使用get方法取得数据 /** * 根据URL试用get方法取得返回的数据 * @param url * URL地址,参数直接挂在URL后面即可 * @return */ public static

  • Java如何使用httpclient检测url状态及链接是否能打开

    目录 使用httpclient检测url状态及链接是否能打开 需要使用到的maven HTTPClient调用远程URL实例 案例描述 使用httpclient检测url状态及链接是否能打开 有时候我们需要检测某个url返回的状态码是不是200或者页面能不能正常打开响应可使用如下代码: 需要使用到的maven <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpc

  • SQL Server 定时访问url激活数据同步示例

    创建作业,执行以下命令 exec master..XP_cmdshell 'http://srm.rapoo.cn?op=sapintferace&i=1&t=1' 激活执行同步网步 以下内容来自网络,介绍如何启用 xp_cmdshell 扩展存储过程将命令 一.简介 xp_cmdshell 扩展存储过程将命令字符串作为操作系统命令 shell 执行,并以文本行的形式返回所有输出. 三.SQL Server 2005中的xp_cmdshell 由于存在安全隐患,所以在SQL Server

  • Java爬虫Jsoup+httpclient获取动态生成的数据

    Java爬虫Jsoup+httpclient获取动态生成的数据 前面我们详细讲了一下Jsoup发现这玩意其实也就那样,只要是可以访问到的静态资源页面都可以直接用他来获取你所需要的数据,详情情跳转-Jsoup爬虫详解,但是很多时候网站为了防止数据被恶意爬取做了很多遮掩,比如说加密啊动态加载啊,这无形中给我们写的爬虫程序造成了很大的困扰,那么我们如何来突破这个梗获取我们急需的数据呢, 下面我们来详细讲解一下如何获取 String startPage="https://item.jd.com/1147

  • HttpClient 请求 URL字符集转码问题

    问题是这样的,我用eclipse发送httpclient请求如下没有问题,但是在idea中就返回400,为毛呢???excuse me? package com.vol.timingTasks; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePassw

  • java 结合jQuery实现跨域名获取数据的方法

    一.什么是跨域? 由于浏览器出于安全的考虑,采取了同源策略的限制,使得jQuery无法直接跨域名互相操作对象或数据.例如:a.com 域名下的 a.html页面利用jQuery无法操作b.com 域名下b.html页面的对象或是数据, 并且默认情况下也不能操作test.a.com域名下的 test.html的 对象或是数据 .只要满足下面条件的jQuery都会视为跨域名: 1.主域相同,子域不同,如xxx.aaa.com和yyy.aaa.com 2.域名相同,端口不同,如xxx.aaa.com:

  • Java实现后台发送及接收json数据的方法示例

    本文实例讲述了Java实现后台发送及接收json数据的方法.分享给大家供大家参考,具体如下: 本篇博客试用于编写java后台接口以及两个项目之间的接口对接功能: 具体的内容如下: 1.java后台给指定接口发送json数据 package com.utils; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Htt

  • java 虚拟机中对象访问详解

    java 虚拟机中对象访问详解 对象访问会涉及到Java栈.Java堆.方法区这三个内存区域. 如下面这句代码: Object objectRef = new Object(); 假设这句代码出现在方法体中,"Object objectRef" 这部分将会反映到Java栈的本地变量中,作为一个reference类型数据出现.而"new Object()"这部分将会反映到Java堆中,形成一块存储Object类型所有实例数据值的结构化内存,根据具体类型以及虚拟机实现的

  • java实现连接mysql数据库单元测试查询数据的实例代码

    1.按照javaweb项目的要求逐步建立搭建起机构,具体的类包有:model .db.dao.test; 具体的架构详见下图: 2.根据搭建的项目架构新建数据库test和数据库表t_userinfo并且添加对应的测试数据; (这里我使用的是绿色版的数据库,具体的下载地址:http://pan.baidu.com/s/1mg88YAc) 具体的建立数据库操作详见下图: 3.编写包中的各种类代码,具体参考代码如下: UserInfo.java /** * FileName: UserInfo.jav

  • java后台发起get请求获取响应数据

    本文实例为大家分享了java后台发起get请求获取响应数据,供大家参考,具体内容如下 学习记录: 话不多说直接上代码: package com.jl.chromeTest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java

随机推荐