`

HttpClient4.3使用总结

阅读更多
1.Get
	public static String getResultWithGet(HttpServletRequest request, String url) throws Exception{
		String result =  null;
		HttpClient client =getClient(); 
		try{
			HttpGet get = new HttpGet(url);
			HttpResponse response = client.execute(get); 
			result = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return result;
	}

2、Post
public static String getResultWithPost(HttpServletRequest request, String url) throws Exception{
		String json = null;
		HttpClient client =getClient(); 
		try{
			HttpPost post = new HttpPost(url);
			@SuppressWarnings("unchecked")
			Map<String, String[]> map = request.getParameterMap();
			Set<String> keySet = map.keySet();
			JSONObject jo = new JSONObject();
			for(String s : keySet){
				if(!"".equals(map.get(s)[0])){
					jo.element(s, map.get(s)[0]);
				}
				
			}
			StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");
			reqEntity.setContentType("application/json");
			post.setEntity(reqEntity);
			HttpResponse response = client.execute(post);
			json = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return json;
	}

3、Put
public static String getResultWithPut(HttpServletRequest request, String url) throws Exception{
		String json = null;
		HttpClient client =getClient(); 
		try{
			HttpPut put = new HttpPut(url);
			@SuppressWarnings("unchecked")
			Map<String, String[]> map = request.getParameterMap();
			Set<String> keySet = map.keySet();
			JSONObject jo = new JSONObject();
			for(String s : keySet){
				if(!"".equals(map.get(s)[0])){
					jo.element(s, map.get(s)[0]);
				}
				
			}
			StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");
			reqEntity.setContentType("application/json");
			put.setEntity(reqEntity);
			HttpResponse response = client.execute(put);
			json = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return json;
	}

4、Delete
public static String getResultWithDelete(HttpServletRequest request, String url) throws Exception{
		String result = null;
		HttpClient client =getClient(); 
		try{
			HttpDelete delete = new HttpDelete(url);
			HttpResponse response  = client.execute(delete);
			result = getResponseBodyAsString(response);
		}finally{
			client.getConnectionManager().shutdown();  
		}
		return result;
	}

5、getResponseBodyAsString
public static String getResponseBodyAsString(HttpResponse response) throws Exception {
		StringBuilder sb = new StringBuilder();
		HttpEntity httpEntity = response.getEntity();  
		if(httpEntity != null){
			httpEntity = new BufferedHttpEntity(httpEntity);  
		    InputStream is = httpEntity.getContent();  
		    BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));
		    String str;
		    while((str=br.readLine())!=null){
		    	sb.append(str);
		    }
		    is.close();
		}
		return sb.toString();
	}

6、文件上传
 public String uploadAttachment(HttpServletRequest request){
		String json = null;
		HttpClient client = TicketUtils.getClient(); 
		try {
			
			HttpPost post = new HttpPost(url);
			
			DiskFileItemFactory fac = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(fac);
			upload.setHeaderEncoding("UTF-8");
			@SuppressWarnings("unchecked")
			List<FileItem> fileList = upload.parseRequest(request);
			Iterator<FileItem> it = fileList.iterator();
			List<File> tempFileList = new ArrayList<File>();
			while (it.hasNext()) {
				FileItem item = it.next();
				if (!item.isFormField()) {
					String fileName = item.getName();
					if (fileName != null)
				     {
				      File file = new File(fileName);
				      item.write(file);
				      MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,Charset.forName("UTF-8")); 
				      FileBody fileBody = new FileBody(file); 
				      multipartEntity.addPart(fileName, fileBody);  
				      post.setEntity(multipartEntity);
				      tempFileList.add(file);
				     }
				}	
			}
			HttpResponse response = client.execute(post);
			json = TicketUtils.getResponseBodyAsString(response);
			//delete temp files
			for(File file : tempFileList){
				file.delete();
			}
		} catch (Exception e) {
			log.error(e);
			json = JsonUtil.getJsonString(Const.ERROR_MESSAGE, EM.TICKET_EXCEPTION);
		}finally{
			client.getConnectionManager().shutdown();
		}
        return json;
    }

7、文件下载
 public void downloadAttachment(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") Integer fileId){
		HttpClient client = TicketUtils.getClient(); 
		try {
	        HttpGet get = new HttpGet(urlStr); 
	        
	        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {  
                public byte[] handleResponse(HttpResponse response)  
                        throws ClientProtocolException, IOException {  
                    HttpEntity entity = response.getEntity();  
                    if (entity != null) {  
                        return EntityUtils.toByteArray(entity);  
                    } else {  
                        return null;  
                    }  
                }  
            };
            byte[] charts = client.execute(get, handler);
	        
	        URL url = new URL(urlStr);
	        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
	        response.reset();
			response.addHeader("Content-disposition",uc.getHeaderField("Content-disposition"));
			OutputStream output = new BufferedOutputStream(response.getOutputStream());
	        output.write(charts); 
	        output.flush();
	        output.close();  
	        get.releaseConnection();
		} catch (Exception e) {
			log.error(e);
		}finally{
			client.getConnectionManager().shutdown();
		}
    }

分享到:
评论

相关推荐

    httpclient4.3工具类

    总结起来,`httpclient4.3工具类`是一个针对HttpClient 4.3的自定义包装,它封装了常见的HTTP操作,提供了便捷的接口供项目中使用。理解这个工具类的内部实现和HttpClient的核心概念,将有助于更好地利用它进行HTTP...

    httpclient4.3 和 httpcore4.4

    总结来说,HttpClient 4.3和HttpCore 4.4的更新为Java开发者提供了更强大、更灵活的HTTP通信能力。它们不仅增强了性能,优化了资源管理,还提升了安全性,使得开发者能够更高效地处理HTTP请求,实现复杂的网络应用...

    httpclient-4.3.jar

    总结,Apache HttpClient 4.3是Java开发中的强大工具,它的灵活性和高效性使得它在处理HTTP通信时具有显著优势。通过深入了解其功能和特性,开发者能够更好地利用HttpClient实现各种复杂的HTTP交互需求。

    httpclient 4.3 中文版

    ### HttpClient 4.3 中文版相关知识点 #### 一、概述 Apache HttpClient 是一个用于构建 HTTP 客户端的应用程序编程接口 (API),属于 Apache Jakarta Commons 的一部分。该库支持 HTTP 协议的最新标准,并提供了...

    httpclient4.3中文教程

    总结来说,HttpClient 4.3 是一个专为 HTTP 通信设计的库,它提供了高效、易用的接口,用于构造和执行各种 HTTP 请求。开发者可以利用它来实现与 Web 服务的交互、爬虫、数据抓取等任务,而无需关心底层的网络细节。...

    HttpClient4.3教程.PDF

    ### HttpClient4.3教程知识点详解 #### 一、引言 在互联网技术中,HTTP协议作为数据通信的基础标准之一,其重要性不言而喻。随着互联网应用的不断发展与变化,HTTP协议也在不断地进化和扩展,以适应更多场景的需求...

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

    总结,HttpClient 4.3提供了处理自签名HTTPS站点的能力,通过自定义SSLContext和TrustManager,我们可以创建一个信任所有证书的HttpClient。这个工具类的实现简化了这个过程,使得在开发和测试环境中与自签名HTTPS...

    HttpClient4.3教程 PDF格式

    总结来说,Apache HttpClient作为一个功能丰富、灵活的HTTP客户端库,为开发者提供了强大工具,以处理各种复杂的HTTP通信场景。然而,开发者在使用时也应当注意HttpClient的适用范围和执行机制,以确保高效和正确的...

    httpclient httpclient-4.3

    本文将深入探讨 HttpClient 4.3.4 版本中的主要特性和使用方法,帮助开发者更好地理解和应用这个强大的工具。 一、HttpClient 4.3.4 的核心特性 1. **多协议支持**:HttpClient 4.3 支持 HTTP/1.1 和 HTTP/2 协议...

    最全最新httpclient4.3.3

    总结,Apache HttpClient 4.3.3是Java开发者进行HTTP通信的强大工具。通过深入理解和应用,我们可以构建高效、可靠的网络应用程序,并在抓包、API调用等场景中游刃有余。了解和掌握HttpClient,无疑是提升Java网络...

    httpclient 4.5 api文档

    以上总结了httpclient 4.5 API文档中关于HTTP客户端的基本使用、连接管理、状态管理以及认证等方面的核心知识点。通过对这些知识点的理解,可以帮助开发者更好地利用httpclient库进行高效、可靠的HTTP通信开发。

    httpClient实例httpClient调用 http/https实例 忽略SSL验证

    总结来说,HttpClient提供了一个强大而灵活的接口来处理HTTP请求,而忽略SSL验证的配置则允许我们在非生产环境中快速地进行测试和开发。但请记住,忽视SSL验证在生产环境中可能会导致安全隐患,务必谨慎对待。

    Spring for Android 2 中文 参考手册 中文文档

    一个关键的例子是HttpClient4.3 for Android,它与Android所有版本兼容,并且可以通过将依赖项添加到项目中来替代本地客户端。如果检测到HttpClient4.3,Spring for Android会自动将其配置为默认的...

    httpclient安卓版

    implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1' } ``` 这样可以确保HttpClient库在Android项目中可用。 2. 针对性修改:在调试百度IOT SDK时,如果遇到HttpClient的兼容问题,可能需要...

    httpclient-4.3.1.jar,httpcore-4.3.2.jar和httpmime-4.3.5.jar

    标题中的“httpclient-4.3.1.jar”,...在版本号上,4.3.x系列代表了一个稳定的版本,可能比早期版本拥有更好的性能和更多的特性。在使用时,开发者需要根据自己的项目需求和兼容性考虑选择合适的版本。

    Android HttpClient Network Lib

    总结来说,`Android HttpClient Network Lib`是一个关于如何在Android应用中使用HttpClient进行网络通信的知识点,涵盖了HttpClient的基本使用方法、优势,以及如何利用提供的jar包和源码进行开发。虽然HttpClient已...

    HttpClient 4.0中文教程

    ### HttpClient 4.0中文教程知识点总结 #### 一、HttpClient概述 **1.1 执行请求** - **HTTP请求**: HTTP请求包含了方法名称(GET、POST等)、URL以及必要的请求头信息。HttpClient允许开发者创建并发送这些请求...

    httpclient

    ### Apache HttpClient 4 教程知识点总结 #### 一、基础知识 ##### 1.1 请求执行 **1.1.1 HTTP请求** Apache HttpClient 库允许开发者构建自定义的HTTP请求,包括GET、POST等常见方法。每个请求都可以携带特定的...

    详解使用angular的HttpClient搭配rxjs

    Angular的HttpClient是一个强大的HTTP客户端库,它被包含在Angular核心模块中,并且是自Angular 4.3版本以来推荐使用的HTTP通信方式,以取代旧版的Http模块。RxJS(Reactive Extensions for JavaScript)是一个基于...

    httpcore-4.3.2和httpclient-4.3.3.jar

    总结来说,Apache HttpClient和HTTPCore是Java开发中进行HTTP通信的强大工具,它们提供的功能丰富且易于使用。HTTPCore作为基础,负责底层的HTTP协议处理;HttpClient则在此基础上构建了一套完善的客户端接口,便于...

Global site tag (gtag.js) - Google Analytics