HttpClient4.3使用总结

1.Get
Java代码   收藏代码
  1. public static String getResultWithGet(HttpServletRequest request, String url) throws Exception{  
  2.     String result =  null;  
  3.     HttpClient client =getClient();   
  4.     try{  
  5.         HttpGet get = new HttpGet(url);  
  6.         HttpResponse response = client.execute(get);   
  7.         result = getResponseBodyAsString(response);  
  8.     }finally{  
  9.         client.getConnectionManager().shutdown();    
  10.     }  
  11.     return result;  
  12. }  

2、Post
Java代码   收藏代码
  1. public static String getResultWithPost(HttpServletRequest request, String url) throws Exception{  
  2.         String json = null;  
  3.         HttpClient client =getClient();   
  4.         try{  
  5.             HttpPost post = new HttpPost(url);  
  6.             @SuppressWarnings("unchecked")  
  7.             Map<String, String[]> map = request.getParameterMap();  
  8.             Set<String> keySet = map.keySet();  
  9.             JSONObject jo = new JSONObject();  
  10.             for(String s : keySet){  
  11.                 if(!"".equals(map.get(s)[0])){  
  12.                     jo.element(s, map.get(s)[0]);  
  13.                 }  
  14.                   
  15.             }  
  16.             StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");  
  17.             reqEntity.setContentType("application/json");  
  18.             post.setEntity(reqEntity);  
  19.             HttpResponse response = client.execute(post);  
  20.             json = getResponseBodyAsString(response);  
  21.         }finally{  
  22.             client.getConnectionManager().shutdown();    
  23.         }  
  24.         return json;  
  25.     }  

3、Put
Java代码   收藏代码
  1. public static String getResultWithPut(HttpServletRequest request, String url) throws Exception{  
  2.         String json = null;  
  3.         HttpClient client =getClient();   
  4.         try{  
  5.             HttpPut put = new HttpPut(url);  
  6.             @SuppressWarnings("unchecked")  
  7.             Map<String, String[]> map = request.getParameterMap();  
  8.             Set<String> keySet = map.keySet();  
  9.             JSONObject jo = new JSONObject();  
  10.             for(String s : keySet){  
  11.                 if(!"".equals(map.get(s)[0])){  
  12.                     jo.element(s, map.get(s)[0]);  
  13.                 }  
  14.                   
  15.             }  
  16.             StringEntity reqEntity = new StringEntity(jo.toString(),"UTF-8");  
  17.             reqEntity.setContentType("application/json");  
  18.             put.setEntity(reqEntity);  
  19.             HttpResponse response = client.execute(put);  
  20.             json = getResponseBodyAsString(response);  
  21.         }finally{  
  22.             client.getConnectionManager().shutdown();    
  23.         }  
  24.         return json;  
  25.     }  

4、Delete
Java代码   收藏代码
  1. public static String getResultWithDelete(HttpServletRequest request, String url) throws Exception{  
  2.         String result = null;  
  3.         HttpClient client =getClient();   
  4.         try{  
  5.             HttpDelete delete = new HttpDelete(url);  
  6.             HttpResponse response  = client.execute(delete);  
  7.             result = getResponseBodyAsString(response);  
  8.         }finally{  
  9.             client.getConnectionManager().shutdown();    
  10.         }  
  11.         return result;  
  12.     }  

5、getResponseBodyAsString
Java代码   收藏代码
  1. public static String getResponseBodyAsString(HttpResponse response) throws Exception {  
  2.         StringBuilder sb = new StringBuilder();  
  3.         HttpEntity httpEntity = response.getEntity();    
  4.         if(httpEntity != null){  
  5.             httpEntity = new BufferedHttpEntity(httpEntity);    
  6.             InputStream is = httpEntity.getContent();    
  7.             BufferedReader br = new BufferedReader(new InputStreamReader(is,"UTF-8"));  
  8.             String str;  
  9.             while((str=br.readLine())!=null){  
  10.                 sb.append(str);  
  11.             }  
  12.             is.close();  
  13.         }  
  14.         return sb.toString();  
  15.     }  

6、文件上传
Java代码   收藏代码
  1. public String uploadAttachment(HttpServletRequest request){  
  2.     String json = null;  
  3.     HttpClient client = TicketUtils.getClient();   
  4.     try {  
  5.           
  6.         HttpPost post = new HttpPost(url);  
  7.           
  8.         DiskFileItemFactory fac = new DiskFileItemFactory();  
  9.         ServletFileUpload upload = new ServletFileUpload(fac);  
  10.         upload.setHeaderEncoding("UTF-8");  
  11.         @SuppressWarnings("unchecked")  
  12.         List<FileItem> fileList = upload.parseRequest(request);  
  13.         Iterator<FileItem> it = fileList.iterator();  
  14.         List<File> tempFileList = new ArrayList<File>();  
  15.         while (it.hasNext()) {  
  16.             FileItem item = it.next();  
  17.             if (!item.isFormField()) {  
  18.                 String fileName = item.getName();  
  19.                 if (fileName != null)  
  20.                  {  
  21.                   File file = new File(fileName);  
  22.                   item.write(file);  
  23.                   MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,Charset.forName("UTF-8"));   
  24.                   FileBody fileBody = new FileBody(file);   
  25.                   multipartEntity.addPart(fileName, fileBody);    
  26.                   post.setEntity(multipartEntity);  
  27.                   tempFileList.add(file);  
  28.                  }  
  29.             }     
  30.         }  
  31.         HttpResponse response = client.execute(post);  
  32.         json = TicketUtils.getResponseBodyAsString(response);  
  33.         //delete temp files  
  34.         for(File file : tempFileList){  
  35.             file.delete();  
  36.         }  
  37.     } catch (Exception e) {  
  38.         log.error(e);  
  39.         json = JsonUtil.getJsonString(Const.ERROR_MESSAGE, EM.TICKET_EXCEPTION);  
  40.     }finally{  
  41.         client.getConnectionManager().shutdown();  
  42.     }  
  43.        return json;  
  44.    }  

7、文件下载
Java代码   收藏代码
  1. public void downloadAttachment(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") Integer fileId){  
  2.     HttpClient client = TicketUtils.getClient();   
  3.     try {  
  4.         HttpGet get = new HttpGet(urlStr);   
  5.           
  6.         ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {    
  7.                public byte[] handleResponse(HttpResponse response)    
  8.                        throws ClientProtocolException, IOException {    
  9.                    HttpEntity entity = response.getEntity();    
  10.                    if (entity != null) {    
  11.                        return EntityUtils.toByteArray(entity);    
  12.                    } else {    
  13.                        return null;    
  14.                    }    
  15.                }    
  16.            };  
  17.            byte[] charts = client.execute(get, handler);  
  18.           
  19.         URL url = new URL(urlStr);  
  20.         HttpURLConnection uc = (HttpURLConnection)url.openConnection();  
  21.         response.reset();  
  22.         response.addHeader("Content-disposition",uc.getHeaderField("Content-disposition"));  
  23.         OutputStream output = new BufferedOutputStream(response.getOutputStream());  
  24.         output.write(charts);   
  25.         output.flush();  
  26.         output.close();    
  27.         get.releaseConnection();  
  28.     } catch (Exception e) {  
  29.         log.error(e);  
  30.     }finally{  
  31.         client.getConnectionManager().shutdown();  
  32.     }  
  33.    } 

转载于:https://my.oschina.net/bluesroot/blog/222396

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值