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 [email protected]
 */
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 [email protected]
 *
 */
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 [email protected]
 *
 *
 */
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

猜你喜欢

转载自daimajia.iteye.com/blog/2327113