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 filesfor(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();} }