HttpClient4.3使用总结

1.Get
Java代码 收藏代码
  1. publicstaticStringgetResultWithGet(HttpServletRequestrequest,Stringurl)throwsException{
  2. Stringresult=null;
  3. HttpClientclient=getClient();
  4. try{
  5. HttpGetget=newHttpGet(url);
  6. HttpResponseresponse=client.execute(get);
  7. result=getResponseBodyAsString(response);
  8. }finally{
  9. client.getConnectionManager().shutdown();
  10. }
  11. returnresult;
  12. }

2、Post
Java代码 收藏代码
  1. publicstaticStringgetResultWithPost(HttpServletRequestrequest,Stringurl)throwsException{
  2. Stringjson=null;
  3. HttpClientclient=getClient();
  4. try{
  5. HttpPostpost=newHttpPost(url);
  6. @SuppressWarnings("unchecked")
  7. Map<String,String[]>map=request.getParameterMap();
  8. Set<String>keySet=map.keySet();
  9. JSONObjectjo=newJSONObject();
  10. for(Strings:keySet){
  11. if(!"".equals(map.get(s)[0])){
  12. jo.element(s,map.get(s)[0]);
  13. }
  14. }
  15. StringEntityreqEntity=newStringEntity(jo.toString(),"UTF-8");
  16. reqEntity.setContentType("application/json");
  17. post.setEntity(reqEntity);
  18. HttpResponseresponse=client.execute(post);
  19. json=getResponseBodyAsString(response);
  20. }finally{
  21. client.getConnectionManager().shutdown();
  22. }
  23. returnjson;
  24. }

3、Put
Java代码 收藏代码
  1. publicstaticStringgetResultWithPut(HttpServletRequestrequest,Stringurl)throwsException{
  2. Stringjson=null;
  3. HttpClientclient=getClient();
  4. try{
  5. HttpPutput=newHttpPut(url);
  6. @SuppressWarnings("unchecked")
  7. Map<String,String[]>map=request.getParameterMap();
  8. Set<String>keySet=map.keySet();
  9. JSONObjectjo=newJSONObject();
  10. for(Strings:keySet){
  11. if(!"".equals(map.get(s)[0])){
  12. jo.element(s,map.get(s)[0]);
  13. }
  14. }
  15. StringEntityreqEntity=newStringEntity(jo.toString(),"UTF-8");
  16. reqEntity.setContentType("application/json");
  17. put.setEntity(reqEntity);
  18. HttpResponseresponse=client.execute(put);
  19. json=getResponseBodyAsString(response);
  20. }finally{
  21. client.getConnectionManager().shutdown();
  22. }
  23. returnjson;
  24. }

4、Delete
Java代码 收藏代码
  1. publicstaticStringgetResultWithDelete(HttpServletRequestrequest,Stringurl)throwsException{
  2. Stringresult=null;
  3. HttpClientclient=getClient();
  4. try{
  5. HttpDeletedelete=newHttpDelete(url);
  6. HttpResponseresponse=client.execute(delete);
  7. result=getResponseBodyAsString(response);
  8. }finally{
  9. client.getConnectionManager().shutdown();
  10. }
  11. returnresult;
  12. }

5、getResponseBodyAsString
Java代码 收藏代码
  1. publicstaticStringgetResponseBodyAsString(HttpResponseresponse)throwsException{
  2. StringBuildersb=newStringBuilder();
  3. HttpEntityhttpEntity=response.getEntity();
  4. if(httpEntity!=null){
  5. httpEntity=newBufferedHttpEntity(httpEntity);
  6. InputStreamis=httpEntity.getContent();
  7. BufferedReaderbr=newBufferedReader(newInputStreamReader(is,"UTF-8"));
  8. Stringstr;
  9. while((str=br.readLine())!=null){
  10. sb.append(str);
  11. }
  12. is.close();
  13. }
  14. returnsb.toString();
  15. }

6、文件上传
Java代码 收藏代码
  1. publicStringuploadAttachment(HttpServletRequestrequest){
  2. Stringjson=null;
  3. HttpClientclient=TicketUtils.getClient();
  4. try{
  5. HttpPostpost=newHttpPost(url);
  6. DiskFileItemFactoryfac=newDiskFileItemFactory();
  7. ServletFileUploadupload=newServletFileUpload(fac);
  8. upload.setHeaderEncoding("UTF-8");
  9. @SuppressWarnings("unchecked")
  10. List<FileItem>fileList=upload.parseRequest(request);
  11. Iterator<FileItem>it=fileList.iterator();
  12. List<File>tempFileList=newArrayList<File>();
  13. while(it.hasNext()){
  14. FileItemitem=it.next();
  15. if(!item.isFormField()){
  16. StringfileName=item.getName();
  17. if(fileName!=null)
  18. {
  19. Filefile=newFile(fileName);
  20. item.write(file);
  21. MultipartEntitymultipartEntity=newMultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,null,Charset.forName("UTF-8"));
  22. FileBodyfileBody=newFileBody(file);
  23. multipartEntity.addPart(fileName,fileBody);
  24. post.setEntity(multipartEntity);
  25. tempFileList.add(file);
  26. }
  27. }
  28. }
  29. HttpResponseresponse=client.execute(post);
  30. json=TicketUtils.getResponseBodyAsString(response);
  31. //deletetempfiles
  32. for(Filefile:tempFileList){
  33. file.delete();
  34. }
  35. }catch(Exceptione){
  36. log.error(e);
  37. json=JsonUtil.getJsonString(Const.ERROR_MESSAGE,EM.TICKET_EXCEPTION);
  38. }finally{
  39. client.getConnectionManager().shutdown();
  40. }
  41. returnjson;
  42. }

7、文件下载
Java代码 收藏代码
  1. publicvoiddownloadAttachment(HttpServletRequestrequest,HttpServletResponseresponse,@PathVariable("fileId")IntegerfileId){
  2. HttpClientclient=TicketUtils.getClient();
  3. try{
  4. HttpGetget=newHttpGet(urlStr);
  5. ResponseHandler<byte[]>handler=newResponseHandler<byte[]>(){
  6. publicbyte[]handleResponse(HttpResponseresponse)
  7. throwsClientProtocolException,IOException{
  8. HttpEntityentity=response.getEntity();
  9. if(entity!=null){
  10. returnEntityUtils.toByteArray(entity);
  11. }else{
  12. returnnull;
  13. }
  14. }
  15. };
  16. byte[]charts=client.execute(get,handler);
  17. URLurl=newURL(urlStr);
  18. HttpURLConnectionuc=(HttpURLConnection)url.openConnection();
  19. response.reset();
  20. response.addHeader("Content-disposition",uc.getHeaderField("Content-disposition"));
  21. OutputStreamoutput=newBufferedOutputStream(response.getOutputStream());
  22. output.write(charts);
  23. output.flush();
  24. output.close();
  25. get.releaseConnection();
  26. }catch(Exceptione){
  27. log.error(e);
  28. }finally{
  29. client.getConnectionManager().shutdown();
  30. }
  31. }

你可能感兴趣的:(httpclient)