`

httpUtil工具和apche httpclient 工具类使用

 
阅读更多
httpUtil请求网络请求工具:

package demo.dcn.service.utils;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * 
 * HttpUtils  工具包
 * @author kun.zhang@downjoy.com
 */
public class HttpUtils {
	
	private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
	private static final int TIMEOUT_IN_MILLIONS = 5000;  
	
	public interface CallBack
	{
		void onRequestComplete(String result);
	}
	/**
	 *  异步的Get请求 
	 * @param url
	 * @param callBack
	 */
	public static void HttpGetAsyn(final String url,final CallBack callBack){
		
		new Thread(){//新建一个线程开始
			public void run(){
				try{
					String result = HttpGet(url);
					if(callBack!=null){
						callBack.onRequestComplete(result);
					}
				}catch(Exception e){
					logger.info("{}-{}", e, e.getMessage());
				}
			}
		}.start();
	}

	
	
	/** 
     * 异步的Post请求 
     * @param urlStr 
     * @param params 
     * @param callBack 
     * @throws Exception 
     */  
	public static void HttpPostAsny(final String url,final String params,final CallBack callBack){
		new Thread()
		{
			public void run()
			{
				try
				{
					String result = HttpPost(url, params);
					if (callBack != null)
					{
						callBack.onRequestComplete(result);
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}

			};
		}.start();
	}
	
	
	 /**  
     * 向指定 URL 发送POST方法的请求  
     *   
     * @param url  
     *            发送请求的 URL  
     * @param param  
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。  
     * @return 所代表远程资源的响应结果  
     * @throws Exception  
     */  
	public static String HttpPost(String url, String params) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try
		{
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("charset", "utf-8");
			conn.setUseCaches(false);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
			conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);

			if (params != null && !params.trim().equals(""))
			{
				// 获取URLConnection对象对应的输出流
				out = new PrintWriter(conn.getOutputStream());
				// 发送请求参数
				out.print(params);
				// flush输出流的缓冲
				out.flush();
			}
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null)
			{
				result += line;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			} catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	/** 
     * Get请求,获得返回数据 
     *  
     * @param urlStr 
     * @return 
     * @throws Exception 
     */  
	public  static String HttpGet(String url) {
		URL surl = null;
		HttpsURLConnection conn = null;
		InputStream is = null;
		ByteArrayOutputStream byteArrayOutputStream  = null;
		try{
			surl = new URL(url);
			conn = (HttpsURLConnection) surl.openConnection();
			//设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");//保持连接
			conn.setReadTimeout(TIMEOUT_IN_MILLIONS);//设置从主机读取数据超时(单位:毫秒) 
			conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);//设置连接主机超时(单位:毫秒)
			//
			if(conn.getResponseCode()==200){
				is =conn.getInputStream();
				byteArrayOutputStream = new ByteArrayOutputStream();
				int len =-1;
				byte[] buf = new byte[128];
				while((len= is.read(buf))!=-1){
					byteArrayOutputStream.write(buf,0,len);
				}
				byteArrayOutputStream.flush();
				return byteArrayOutputStream.toString();
			}else{
				 throw new RuntimeException(" responseCode is not 200 ... ");
			}
			
		}catch(Exception e){
			e.printStackTrace();
		} finally  
        {  
            try  
            {  
                if (is != null)  
                    is.close();  
            } catch (IOException e)  
            {  
            }  
            try  
            {  
                if (byteArrayOutputStream != null)  
                	byteArrayOutputStream.close();  
            } catch (IOException e)  
            {  
            }  
            conn.disconnect();  
        }  
        return null ; 
	}
	
	/**
	 * httpPost maps 请求
	 * param url 地址
	 * param params 参数
	 * param encode 编码
	 */
	public static String HttpPost(String url, Map<String,String> params,String encode) {
		OutputStream  out = null;
		String result = "";
		try
		{
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl
					.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("charset", encode);
			conn.setUseCaches(false);
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setReadTimeout(TIMEOUT_IN_MILLIONS);
			conn.setConnectTimeout(TIMEOUT_IN_MILLIONS);
			StringBuffer stringBuffer = new StringBuffer();
			if (params != null && !params.isEmpty())
			{
				  for (Map.Entry<String, String> entry : params.entrySet()) {
				        try {
				          stringBuffer
				              .append(entry.getKey())
				              .append("=")
				              .append(URLEncoder.encode(entry.getValue(), encode))
				              .append("&");
				        } catch (UnsupportedEncodingException e) {
				          e.printStackTrace();
				        }
				  }
				  stringBuffer.deleteCharAt(stringBuffer.length() - 1);
						  
				  byte[] mydata = stringBuffer.toString().getBytes();
				// 获取URLConnection对象对应的输出流
					out = conn.getOutputStream();
					// 发送请求参数
					out.write(mydata);
					// flush输出流的缓冲
					out.flush();
					int responseCode  = conn.getResponseCode();//获取服务器响应状态码
					if(responseCode==200){
						 // 获得输入流,从服务器端获得数据
						InputStream inputStream = conn.getInputStream();
						return (changeInputStream(inputStream,encode));
					}
				}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
			} catch (IOException ex)
			{
				ex.printStackTrace();
			}
		}
		return result;
	}

	private static String changeInputStream(InputStream inputStream,
			String encode) {
			ByteArrayOutputStream  arrayOutputStream = new ByteArrayOutputStream();
			byte[] data = new byte[1024];
			int len =0;
			String result ="";
			if(inputStream!=null){
				try{
				while((len =inputStream.read(data))!=-1){
					arrayOutputStream.write(data,0,len);
				}
				result  = new String(arrayOutputStream.toByteArray(),encode);//按照编码读取服务器数据
				}catch(Exception e){
					
				}
			}
		return result;
	}
}


HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient。现在HttpClient最新版本为 HttpClient 4.5 (GA) (2015-09-11)


apcheHttpUitls 请求工具:

package demo.dcn.service.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

import demo.dcn.common.HttpResult;


/**
 * apache common HttpClient 4.2 以上版本 HTTP请求
 * 配带连接池
 * @author kun.zhang@downjoy.com
 *
 */
public class ApacheHttpUtils {

	private static final Logger logger= LoggerFactory.getLogger(ApacheHttpUtils.class);
	private RequestConfig requestConfig = RequestConfig.custom()
			.setSocketTimeout(15000).setConnectTimeout(15000)
			.setConnectionRequestTimeout(15000).build();
	
	private static ApacheHttpUtils instance = null;
	public ApacheHttpUtils() {
		super();
	}
	public static ApacheHttpUtils getInstance(){
		if(instance==null){
			instance  = new ApacheHttpUtils();
		}
		return instance;
	}
	/**
	 * 发送 post请求
	 * @param url
	 * @return
	 */
	public HttpResult sendHttpPost(String url){
		HttpPost httpPost = new HttpPost(url);
		return sendHttpPost(httpPost);
	}
	/**
	 * 发送 post 请求
	 * @param url 地址   
	 * @param params 参数(格式:key1=value1&key2=value2)
	 * @return
	 */
	public HttpResult sendHttpPost(String url,String params){
		HttpPost httpPost = new HttpPost(url);
		try{
			StringEntity stringEntity = new StringEntity(params,"UTF-8");
			stringEntity.setContentType("application/x-www-form-urlencoded");
			httpPost.setEntity(stringEntity);
		}catch(Exception e){
			e.printStackTrace();
			logger.info("{}-{}", "网络超时", e.getMessage());
		}
		return sendHttpPost(httpPost);
	}
	/**
	 * post 请求 map 参数
	 * @param url
	 * @param maps
	 * @return
	 */
	public HttpResult sendHttpPost(String url,Map<String,String> maps){
		HttpPost httpPost = new HttpPost(url);
		try{
			List<NameValuePair>  nameValuePairs = new ArrayList<NameValuePair>();
			if(maps!=null){
				for (String key  : maps.keySet()) {
					nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
				}
				httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
				return sendHttpPost(httpPost);
			}else{
				return sendHttpPost(httpPost);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.info("{}-{}", "网络超时", e.getMessage());
		}
		return null;
	}
	/**
	 * 发送 post请求(带文件)
	 * @param url
	 * @param maps
	 * @param files  附件
	 * @return
	 */
	public HttpResult sendHttpPost(String url,Map<String,String> maps,List<File> files){
		HttpPost httpPost = new HttpPost(url);
		try{
			 MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create(); 
			 if(maps!=null){
					for (String key  : maps.keySet()) {
						meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
					}
					for (File file : files) {
						FileBody fileBody = new FileBody(file);
						meBuilder.addPart("files", fileBody);
					}
					HttpEntity httpEntity  = meBuilder.build();
					httpPost.setEntity(httpEntity);
					return sendHttpPost(httpPost);
				}else{
					return sendHttpPost(httpPost);
				}
		}catch(Exception e){
			e.printStackTrace();
			logger.info("{}-{}", "网络超时", e.getMessage());
		}
		return null;
	}
	/**
	 * 发送Post请求  
	 * @param httpPost
	 * @return
	 */
	
	private HttpResult sendHttpPost(HttpPost httpPost) {
		CloseableHttpClient  httpClient = null;
		CloseableHttpResponse httpResponse = null;
		HttpEntity entity = null;
		String responseContent  = null;
		try{ // 创建默认的httpClient实例. 
			httpClient = HttpClients.createDefault();
			httpPost.setConfig(requestConfig);
			httpResponse = httpClient.execute(httpPost);
			entity = httpResponse.getEntity();
			responseContent  = EntityUtils.toString(entity, "UTF-8");
			logger.info("{}-{}",httpResponse.getStatusLine().getStatusCode(),responseContent); 
		}catch(Exception e){
			e.printStackTrace();
			logger.error("{}-{}", e.getMessage(), e);
			return new HttpResult(httpResponse.getStatusLine().getStatusCode(), responseContent);  
		}finally {              
			 try {                  
				 // 关闭连接,释放资源                 
				 if (httpResponse != null) {                      
					 httpResponse.close();                  
					 }                  
				 if (httpClient != null) {                      
					 httpClient.close();                  
					 }              
				 } catch (IOException e) {                  
					 e.printStackTrace();              
					 }          
			 }          
			return  new HttpResult(httpResponse.getStatusLine().getStatusCode(),responseContent);      
	}
	
	/**      
	 * 发送 get请求      
	 *  @param httpUrl      
	 * */     
	public HttpResult sendHttpGet(String httpUrl) {          
		 HttpGet httpGet = new HttpGet(httpUrl);
		 // 创建get请求          
		 return sendHttpGet(httpGet);       
	}
	/**      
	 *  发送 get请求Https      
	 * @param httpUrl      
	 * */      
	public HttpResult sendHttpsGet(String httpUrl) {          
		 HttpGet httpGet = new HttpGet(httpUrl);
		 // 创建get请求          
		 return sendHttpsGet(httpGet);      
		 }  
	/**      
	 *发送Get请求     
	 * @param httpPost      
	 *@return      
	 *  
	 */      
	private HttpResult sendHttpGet(HttpGet httpGet) {          
		 CloseableHttpClient httpClient = null;          
		 CloseableHttpResponse response = null;          
		 HttpEntity entity = null;          
		 String responseContent = null;          
		 try {              
			 // 创建默认的httpClient实例.              
			 httpClient = HttpClients.createDefault();              
			 httpGet.setConfig(requestConfig);              
			 // 执行请求              
			 response = httpClient.execute(httpGet);              
			 entity = response.getEntity();              
			 responseContent = EntityUtils.toString(entity, "UTF-8"); 
			 logger.info("{}-{}",response.getStatusLine().getStatusCode(),responseContent); 
			 } catch (Exception e) {              
				 e.printStackTrace();
				 logger.error("{}-{}", e.getMessage(), e);
				 return new HttpResult(response.getStatusLine().getStatusCode(), responseContent);  
				 } finally {              
					 try {                  
						 // 关闭连接,释放资源                  
						 if (response != null) {                      
							 response.close();                  
							 }                  
						 if (httpClient != null) {                      
							 httpClient.close();                  
							 }              
						 } catch (IOException e) {                  
							 e.printStackTrace();              
							 }          
					 }          
		 return new HttpResult(response.getStatusLine().getStatusCode(),responseContent);      
		 } 
	
	/**      
	 * 
	 * 发送Get请求Https      
	 *  @param httpPost      
	 *  @return       
	 * */      
	private HttpResult sendHttpsGet(HttpGet httpGet) {          
		 CloseableHttpClient httpClient = null;          
		 CloseableHttpResponse response = null;          
		 HttpEntity entity = null;          
		 String responseContent = null;          
		 try {              
			 // 创建默认的httpClient实例.              
			 PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));              
			 DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);              
			 httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();              
			 httpGet.setConfig(requestConfig);              
			 // 执行请求              
			 response = httpClient.execute(httpGet);              
			 entity = response.getEntity();              
			 responseContent = EntityUtils.toString(entity, "UTF-8");  
			 logger.info("{}-{}",response.getStatusLine().getStatusCode(),responseContent); 
			 } catch (Exception e) {  
				 e.printStackTrace(); 
				 logger.error("{}-{}", e.getMessage(), e);
				 return new HttpResult(response.getStatusLine().getStatusCode(), responseContent);  
				 } finally {              
					 try {                  
						 // 关闭连接,释放资源                  
						 if (response != null) {                      
							 response.close();                  
							 }                  
						 if (httpClient != null) {                      
							 httpClient.close();                  
							 }              
						 } catch (IOException e) {                  
							 e.printStackTrace();              
							 }          
					 }          
		 return new HttpResult(response.getStatusLine().getStatusCode(), responseContent);      
		 }  
}


HttpResult 返回数据  :

package demo.dcn.common;

/**
 * 映射http 请求结果
 * @author kun.zhang@downjoy.com
 *
 *
 */
public class HttpResult {
	private Integer statusCode;//返回的状态码
	private String data;//返回的数据
	/**
	 * @return the statusCode
	 */
	public Integer getStatusCode() {
		return statusCode;
	}

	/**
	 * @param statusCode the statusCode to set
	 */
	public void setStatusCode(Integer statusCode) {
		this.statusCode = statusCode;
	}

	/**
	 * @return the data
	 */
	public String getData() {
		return data;
	}

	/**
	 * @param data the data to set
	 */
	public void setData(String data) {
		this.data = data;
	}

	public HttpResult(Integer statusCode, String data) {
		super();
		this.statusCode = statusCode;
		this.data = data;
	}

	public HttpResult() {
		super();
	}
}

httpclient 工具类还可以用
okhttp 接口:

RequestBody formBody = new FormBody.Builder()
                .add("companyId", getCompanyEnum(LabelTypeEnum.fromCode(labelTypeEnum)).toString()).add("trackNumber",packetOut.getLabel())
                .build();
        Request request = new Request.Builder().url(GET_TRACK).post(formBody).build();
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            int code = response.code();
            System.out.println(response.isSuccessful());
            if(response.code()<200||response.code()>=400){
                logger.error("jiayuTrack getTrackByCompany Code{}", code);
            }else{
                String data = response.body().string();
                System.out.println(data);
                if(!StringUtils.isBlank(data)){
                    JiayuTrackVo trackVo = JSONObject.parseObject(data, JiayuTrackVo.class);
                    if(trackVo.getSuccess()){
                        TrackInfo info =   JSONObject.parseObject(trackVo.getT(),TrackInfo.class);
                        if(info!=null&&(info.getStatus()==1002 || info.getStatus() == 1003)){//表示请求有返回数据
                            List<TrackEvent> eventList =  JSONArray.parseArray(info.getEvents(),TrackEvent.class);
                            pxTrack(eventList,result,info.getCompanyId(),packetOut.getLabel());
                        }
                    }
                }

            }




在github 上面有一个很好的工程源码讲述了okhttp 可以去下载
https://github.com/square/okhttp.git



httpclient 参考 我用的是  4.5 以上的版本 跟之前版本写法有很大不同。
<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpclient</artifactId>
		    <version>4.5.2</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.httpcomponents</groupId>
		    <artifactId>httpmime</artifactId>
		    <version>4.5.2</version>
		</dependency>

http://www.cnblogs.com/chenying99/p/3735282.html

分享到:
评论

相关推荐

    HttpClient 4.5 封装的工具类 HttpUtil 可用于爬虫和模拟登陆

    基于Apache HttpClient 4.5.2 封装的工具类 HttpUtil 可用于爬虫和模拟登陆。使用新的语法后比3.*版本的速度感觉有提升。使用后注意资源的释放 pom 部分,应该不全,需要用的根据代码的import去找maven资源即可。 ...

    httpUtil httpclient 登陆携带cookie访问下一个连接

    在这个过程中,`HttpUtil.java`可能是一个自定义的工具类,包含了使用`httpclient`进行HTTP操作的实用方法。它可能会包含创建`HttpClient`、构建请求、解析响应等功能,简化了代码的复用和维护。 总之,`httpclient...

    http请求工具类HttpClientUtil,get,post请求(csdn)————程序.pdf

    总结,HttpClientUtil 是一个方便的工具类,封装了 Apache HttpClient 库,简化了 HTTP 请求的发送,特别是对于 GET 和 POST 请求。它使用了 Fastjson 和 Guava 库来处理数据的序列化和集合操作,提高了代码的可读性...

    HttpUtil,支持data-form、SSL等

    3. **所有jar包包含在内**:在提供的压缩文件中,`HttpUtil` 包含了所有必要的jar包,这意味着开发者无需额外下载其他依赖,可以直接在项目中使用这个工具类。这些jar包可能包含了HTTP客户端库(如Apache HttpClient...

    HttpUtils 发送http请求工具类(实例讲解)

    HttpUtils 工具类是基于 Apache HttpClient 库开发的,它提供了一些便捷的方法来发送 HTTP 请求和处理响应结果。该工具类提供了多种方法来发送 GET、POST、PUT、DELETE 等请求,并且支持设置超时时间、代理服务器、...

    HttpClientUtil工具类 里面包含GET POST 及返回值处理

    HttpClientUtil工具类是Java开发中一个非常实用的工具,它封装了Apache的HttpClient库,用于简化HTTP请求的发送,包括GET和POST方法。这个工具类的主要优点在于它可以帮助开发者快速地构建网络请求,无需深入了解...

    httpclient工具类

    HTTPClient工具类是Java开发中用于执行HTTP请求的常用库,尤其在处理复杂的HTTP操作时,如发送POST、GET请求,处理cookies,管理session等。Apache的Commons HttpClient库是这个领域的一个经典选择,它提供了丰富的...

    httpclient

    `commons-httpclient-3.0.jar`是Apache HttpClient 3.0版本的二进制库文件,包含了HttpClient的所有类和方法,开发者可以通过导入这个库来使用HttpClient的相关功能。而`HttpUtil.java`可能是一个自定义的Java类,...

    java使用HttpClient通过url下载文件到本地

    在Eclipse中使用HttpClient,首先需要将相关的jar包添加到项目的类路径中。这些jar包通常包括`httpclient`, `httpcore`, `httpmime`等,确保HttpClient库的所有依赖都已包含。 3. **下载文件的基本步骤**: - **...

    Http工具类HttpUtil.java

    Http工具类HttpUtil.java:这个文件是工作用到的工具类,上传上来以后自己用到或者有同学也需要。 maven项目添加如下的jar包依赖,文件放到项目中修改一下package就可以直接使用了。 &lt;groupId&gt;org.apache....

    基于HttpClient 4.3的可访问自签名HTTPS站点的新版工具类

    为了提高代码的可重用性和可维护性,我们可以将这些步骤封装到一个工具类中,比如`HttpUtil`。 ```java public class HttpUtil { public static CloseableHttpResponse executeGetWithSelfSigned(String url) ...

    Httpclient所需jar包

    这个压缩包包含的正是使用HttpClient所需的三个核心jar包:`commons-codec-1.4.jar`、`commons-httpclient-3.0.1.jar`和`commons-logging-1.1.1.jar`。 首先,我们来详细了解一下这三个jar包的功能: 1. **`...

    http发送Get和Post请求工具类

    `sendGetRequest`方法会构建一个URL字符串,将所有参数附加到URL路径后,然后使用`HttpURLConnection`或者第三方库如Apache HttpClient、OkHttp来发起请求。返回的数据通常以字符串形式。 2. **POST请求**: - ...

    27个java工具类

    12. **HttpUtil**:HTTP请求工具类,用于发送HTTP请求并接收响应,常用于网络通信和API调用。Java的`java.net.HttpURLConnection`或第三方库如Apache HttpClient可以实现这些功能。 以上仅为部分工具类的简要说明,...

    HttpUtils Java get post 工具类

    "HttpUtils Java get post 工具类" 提供了便捷的方法来发送GET和POST请求,简化了网络请求的操作。以下是对这两个主要HTTP方法的详细解释以及如何在Java中实现它们。 **1. GET方法** GET是HTTP中最常见的请求方法,...

    httpclient 绕开HTTPS证书校验

    在`httpclient-4.2.5.jar`这个版本中,我们可以找到实现这一功能的相关类和方法。`httpcore-4.2.4.jar`则是`httpclient`的基础库,提供了HTTP协议的核心组件,如连接管理、请求和响应模型等。 为了绕过HTTPS证书...

    http请求工具类

    在IT行业中,HTTP请求工具类是开发者经常使用的工具,它简化了向服务器发送HTTP请求的过程。这个名为"HttpUtil"的Java文件很可能是为开发者提供一个...理解和使用这样的工具类,能够提升开发效率,减少出错的可能性。

    JAVA 发送http请求工具类

    本文将详细解析如何使用Java实现HTTP和HTTPS的GET与POST请求,并结合提供的类文件名称(HttpsHandler.java、HttpUtil.java、NetUtil.java)探讨可能的实现方式。 首先,`HttpUtil`类通常用于封装HTTP请求的操作。在...

    httpUtils请求工具类

    这个工具类可能使用了Apache HttpClient库或者Java内置的HttpURLConnection来实现这些请求。HttpClient库提供了更高级的功能,如自定义头信息、设置超时和处理重定向,而HttpURLConnection则是Java的标准API,更轻量...

    HttpUtil-master

    在Java开发中,处理HTTP请求通常有多种方式,例如使用内置的`java.net.URL`和`java.net.HttpURLConnection`,或者使用第三方库如Apache HttpClient或OkHttp。这些库提供更高级的功能,如连接池管理、自动重试、请求...

Global site tag (gtag.js) - Google Analytics