`
sungang_1120
  • 浏览: 323549 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类

HttpClientUtil封装二

 
阅读更多
package com.web.util;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class ServiceInterfaceLinkTool{
	public String invokeServiceMethod(String url,Map<String,String> params,Map<String, String> header) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		 HttpResponse response = null;
	        HttpEntity entity = null;
	        httpclient.getParams().setParameter(
	                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
	        HttpPost httpost = new HttpPost(url);           //引号中的参数是:action的地址
	        if (header!=null&&header.size()>0) {
	        	for (String key : header.keySet()) {
	        		httpost.setHeader(key,header.get(key));
				}
			}
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
	        for (String keyItem : params.keySet()) {
	        	String key=keyItem;
	        	String value=params.get(keyItem);
	        	nvps.add(new BasicNameValuePair(key,value));  
			}
	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));            //将参数传入post方法中
	        response = httpclient.execute(httpost);                                               //执行
	        StatusLine stateLine=response.getStatusLine();
			int statusCode=stateLine.getStatusCode();
			if (statusCode!=200) {
				httpclient.getConnectionManager().shutdown();
				return "";
			}
	        entity = response.getEntity();                                                             //返回服务器响应
	        try{
	            String responseString = null;
	            if (entity != null) {
	            responseString = EntityUtils.toString(entity);      
	            }
	            return responseString;
	        } finally {
	            if (httpclient!=null)                          
	            	httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
	        }
	       
	}
	public String invokeServiceMethod(String url) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		HttpResponse response = null;
		HttpEntity entity = null;
		httpclient.getParams().setParameter(
				ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
		HttpGet httpGet = new HttpGet(url);           //引号中的参数是:action的地址
		response = httpclient.execute(httpGet);                                               //执行
		entity = response.getEntity();                                                             //返回服务器响应
//		response.getStatusLine();
		try{
			String responseString = null;
			if (entity != null) {
				responseString = EntityUtils.toString(entity);      
			}
			return responseString;
		} finally {
			if (httpclient!=null)                          
				httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
		}
		
	}
	public Boolean urlCheck(String url) throws ClientProtocolException, IOException{
		if (StringUtils.isBlank(url)) {
			return false;
		}
		HttpClient httpclient=new DefaultHttpClient();
		HttpResponse response = null;
		httpclient.getParams().setParameter(
				ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
		HttpGet httpGet = new HttpGet(url);           //引号中的参数是:action的地址
		response = httpclient.execute(httpGet);                                               //执行
			StatusLine stateLine=response.getStatusLine();
			int statusCode=stateLine.getStatusCode();
			if (statusCode==200) {
				return true;
			}
			if (httpclient!=null)                          
				httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
		return false;
		
	}
/*	public String invokeServiceMethod(String url,Map<String,String> params) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		 HttpResponse response = null;
	        HttpEntity entity = null;
	        httpclient.getParams().setParameter(
	                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
	        HttpPost httpost = new HttpPost(url);           //引号中的参数是:action的地址
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
	        for (String keyItem : params.keySet()) {
	        	String key=keyItem;
	        	String value=params.get(keyItem);
	        	nvps.add(new BasicNameValuePair(key,value));  
			}
	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));            //将参数传入post方法中
	        response = httpclient.execute(httpost);                                               //执行
	        entity = response.getEntity();                                                             //返回服务器响应
	        try{
	            String responseString = null;
	            if (entity != null) {
	            responseString = EntityUtils.toString(entity);      
	            }
	            return responseString;
	        } finally {
	            if (httpclient!=null)                          
	            	httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
	        }
	       
	}*/
	public String invokeServiceMethod(String url,Map<String,String> params,Map<String, String> header,File[] files,String propName) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		HttpResponse response = null;
		HttpEntity entity = null;
		httpclient.getParams().setParameter(
				ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
		HttpPost httpost = new HttpPost(url);           //引号中的参数是:action的地址
        if (header!=null&&header.size()>0) {
        	for (String key : header.keySet()) {
        		httpost.setHeader(key,header.get(key));
			}
		}
		MultipartEntity multipartEntity=new MultipartEntity();
		for (String keyItem : params.keySet()) {
			multipartEntity.addPart(keyItem, new StringBody(params.get(keyItem), Charset.forName("UTF-8")));
		}
		if (files!=null) {
			for (File file : files) {
				multipartEntity.addPart(propName, new FileBody(file));
			}
		}
		httpost.setEntity(multipartEntity);            //将参数传入post方法中
		response = httpclient.execute(httpost);                                               //执行
		entity = response.getEntity();                                                             //返回服务器响应
		try{
			String responseString = null;
			if (entity != null) {
				responseString = EntityUtils.toString(entity);      
			}
			return responseString;
		} finally {
			if (httpclient!=null)                          
				httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
		}
		
	}
	/**
	 * 执行webservice接口
	 * @param url 接口地址
	 * @param params 参数 
	 * @param files 需上传的文件
	 * @param propName 上传文件对应的name键
	 * @return
	 * @throws Exception
	 */
	public String invokeServiceMethod(String url,List<Map<String, String>> params,File[] files,String propName) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		HttpResponse response = null;
		HttpEntity entity = null;
		httpclient.getParams().setParameter(
				ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
		HttpPost httpost = new HttpPost(url);           //引号中的参数是:action的地址
		MultipartEntity multipartEntity=new MultipartEntity();
		for (Map<String, String> map : params) {
			for (String keyItem : map.keySet()) {
				multipartEntity.addPart(keyItem, new StringBody(map.get(keyItem), Charset.forName("UTF-8")));
			}
		}
		for (File file : files) {
			multipartEntity.addPart(propName, new FileBody(file));
		}
		httpost.setEntity(multipartEntity);            //将参数传入post方法中
		response = httpclient.execute(httpost);                                               //执行
		entity = response.getEntity();                                                             //返回服务器响应
		try{
			String responseString = null;
			if (entity != null) {
				responseString = EntityUtils.toString(entity);      
			}
			return responseString;
		} finally {
			if (httpclient!=null)                          
				httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
		}
		
	}
	public String invokeServiceMethod(String url, Map<String, String> params) throws Exception {
		return invokeServiceMethod(url, params, new HashMap<String, String>());
	}
	
	
	public String invokeServiceMethod(String url,Map<String,String> params,Map<String, String> header,HttpServletResponse httpServletResponse) throws Exception{
		HttpClient httpclient=new DefaultHttpClient();
		 HttpResponse response = null;
	        HttpEntity entity = null;
	        httpclient.getParams().setParameter(
	                ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);  //设置cookie的兼容性
	        HttpPost httpost = new HttpPost(url);           //引号中的参数是:action的地址
	        if (header!=null&&header.size()>0) {
	        	for (String key : header.keySet()) {
	        		httpost.setHeader(key,header.get(key));
				}
			}
	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();  
	        for (String keyItem : params.keySet()) {
	        	String key=keyItem;
	        	String value=params.get(keyItem);
	        	nvps.add(new BasicNameValuePair(key,value));  
			}
	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));            //将参数传入post方法中
	        response = httpclient.execute(httpost);                                               //执行
	        StatusLine stateLine=response.getStatusLine();
			int statusCode=stateLine.getStatusCode();
			if (statusCode!=200) {
				httpclient.getConnectionManager().shutdown();
				return "错误";
			}
	        entity = response.getEntity();                                                             //返回服务器响应
	        try{
	            if (entity != null&&entity.isStreaming()) {
	            	//设置相应头
	            	for (Header nameValuePair : response.getAllHeaders()) {
	            		httpServletResponse.setHeader(nameValuePair.getName(), nameValuePair.getValue());
					}
					byte[] temp = new byte[1024*10];
					int num=0;
					InputStream in = entity.getContent();      
					while ((num=in.read(temp))>0) {
						httpServletResponse.getOutputStream().write(temp,0,num);
					}
				}
	        } finally {
	            if (httpclient!=null)                          
	            	httpclient.getConnectionManager().shutdown();                                                // release connection gracefully
	        }
			return null;
	       
	}
	
	
}

 

分享到:
评论

相关推荐

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

    2. **HttpClientUtil的核心功能**: - **GET请求**:HttpClientUtil通常包含一个方法,用于发送GET请求。开发者只需要提供URL,工具类会自动构造请求并获取响应。返回值通常是一个包含了响应内容的字符串,方便...

    HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件

    2. POST请求:对于POST请求,HttpClientUtil会创建HttpPost对象,使用NameValuePair或HttpEntity来构建请求体。NameValuePair用于简单键值对数据,而HttpEntity适用于更复杂的数据格式,如MultipartEntity,它可以...

    HttpClientUtil

    2. **线程安全**:为了支持多线程环境,HttpClientUtil通常设计为线程安全的,这意味着多个线程可以同时使用同一实例而不会引发冲突。 3. **错误处理**:工具类会捕获并处理可能发生的异常,例如网络中断、超时、...

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

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

    httpclientutil

    2. **HttpClientUtil 类**:通常,开发者会创建一个辅助类 HttpClientUtil,封装 HttpClient 的常用操作,如构建HttpGet、HttpPost对象,设置请求头,处理响应等,以减少代码重复和提高可维护性。 3. **发送 JSON ...

    HttpClientUtil.java

    java httpclient 进行的简单封装,方便大家对httpclient使用。

    httpclientUtil

    2.基于HttpAsycClient-4.1封装的异步HttpClient工具类; 3.javanet包下面是基于jdk自带的UrlConnection进行封装的。 前2个工具类支持插件式配置Header、插件式配置httpclient对象,这样就可以方便地自定义header信息...

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

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

    webUtils-安卓对HttpClient的简单封装

    自己对HttpClient的简单封装,目前只封装了post方式的请求

    对于C#(HttpClient)方式网络请求的封装

    2. **封装的设计**:讨论如何设计一个网络请求的通用接口或类,比如定义方法如`SendGetAsync`和`SendPostAsync`,以便在不同的场景下复用。 3. **错误处理**:讲解如何在封装中加入异常处理机制,确保在请求失败时...

    httpclient.jar包下载

    2. **请求和响应模型**:HttpClient使用HttpRequest和HttpResponse对象封装HTTP请求和响应,便于处理请求头、请求体和响应头、响应体。 3. **身份验证和安全**:HttpClient支持多种身份验证机制,包括基本认证、...

    HttpClient接口调用工具类(附带demo)

    2. **Get请求**: Get请求是最简单的HTTP请求,用于从服务器获取资源。HttpClient中的`HttpGet`类可以用来创建GET请求。只需提供URL作为构造函数的参数,然后同样通过`HttpClient`的`execute`方法执行请求。 3. **...

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

    2. **配置HttpClient**:为了管理HTTP连接,我们需要创建一个`HttpClient`实例。可以使用`HttpClientBuilder`来定制各种设置,如超时时间、重试策略、连接池等。 3. **执行请求**:调用`HttpClient`的`execute`方法...

    淘淘商城07-工具类

    工具类可能会包含对HttpClient的进一步封装,提供更友好的接口,例如自动处理重定向、编码问题、超时设置等,使得网络请求更加便捷和稳定。 4. **JsonUtil**: JSON(JavaScript Object Notation)是一种轻量级的...

    httpclient-all-final-4.5.1.jar

    基于httpclient-all-final-4.5.1.jar封装的HttpClientUtil工具类发送http请求

    jtool-httpclient:httpclient上的简单封装

    HttpClientUtil.setRequestHeader("User-Agent", "MyApp/1.0"); HttpClientUtil.setTimeout(5000); // 设置超时时间为5秒 ``` 三、响应处理 jtool-httpclient将HTTP响应封装为一个易于操作的对象,可以方便地...

    HttpClient工具类

    在HttpClientUtil中,可以提供一个方法如`httpPostRequest(String url, Map, String&gt; params)`,它接受URL和参数Map,将参数转换为NameValuePair列表,通过`UrlEncodedFormEntity`编码后设置到`HttpPost`对象中,...

    java HttpClient 发送GET请求和带有表单参数的POST请求教程例子

    除了创建`HttpClient`和`HttpPost`对象外,还需要创建一个`List&lt;NameValuePair&gt;`来存储表单参数,然后将其封装到`UrlEncodedFormEntity`中,再设置到`HttpPost`对象上。 ##### 示例代码: ```java public static ...

    JAVA发送HttpClient请求及接收请求完整代码实例

    在实际开发中,为了提高代码的可重用性和易维护性,通常会将这些步骤封装到一个单独的工具类中,如`HttpClientUtil`。这个类可能包含发送GET、POST请求的方法,以及其他辅助功能,如处理超时、重试策略等。 ```java...

Global site tag (gtag.js) - Google Analytics