码迷,mamicode.com
首页 > Web开发 > 详细

httpClient工具类

时间:2017-09-08 18:13:05      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:imp   mozilla   size   根据   exe   sum   new   多个   method   

  1 package com.ideal.common.util;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.DataInputStream;
  5 import java.io.DataOutputStream;
  6 import java.io.File;
  7 import java.io.FileInputStream;
  8 import java.io.IOException;
  9 import java.io.InputStreamReader;
 10 import java.io.OutputStream;
 11 import java.io.OutputStreamWriter;
 12 import java.net.HttpURLConnection;
 13 import java.net.URL;
 14 import java.net.URLConnection;
 15 import java.util.ArrayList;
 16 import java.util.HashMap;
 17 import java.util.Iterator;
 18 import java.util.List;
 19 import java.util.Map;
 20 import java.util.Map.Entry;
 21 
 22 import javax.activation.MimetypesFileTypeMap;
 23 
 24 import org.apache.http.HttpEntity;
 25 import org.apache.http.HttpResponse;
 26 import org.apache.http.NameValuePair;
 27 import org.apache.http.client.HttpClient;
 28 import org.apache.http.client.entity.UrlEncodedFormEntity;
 29 import org.apache.http.client.methods.HttpPost;
 30 import org.apache.http.impl.client.DefaultHttpClient;
 31 import org.apache.http.message.BasicNameValuePair;
 32 import org.apache.http.util.EntityUtils;
 33 
 34 
 35 @SuppressWarnings("deprecation")
 36 public class HttpXmlClient {
 37      /**
 38      * 向指定URL发送GET方法的请求
 39      * 
 40      * @param url
 41      *            发送请求的URL
 42      * @param param
 43      *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
 44      * @return URL 所代表远程资源的响应结果
 45      */
 46     public static String sendGet(String url, String param) {
 47         String result = "";
 48         BufferedReader in = null;
 49         try {
 50             String urlNameString = url;
 51             if (param != null) {
 52                 urlNameString = urlNameString + "?" + param;
 53             }
 54             URL realUrl = new URL(urlNameString);
 55             // 打开和URL之间的连接
 56             URLConnection connection = realUrl.openConnection();
 57             // 设置通用的请求属性
 58             connection.setRequestProperty("accept", "*/*");
 59             connection.setRequestProperty("connection", "Keep-Alive");
 60             connection.setRequestProperty("user-agent",
 61                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
 62             // 建立实际的连接
 63             connection.connect();
 64             // 获取所有响应头字段
 65             Map<String, List<String>> map = connection.getHeaderFields();
 66             // 遍历所有的响应头字段
 67             for (String key : map.keySet()) {
 68                 System.out.println(key + "--->" + map.get(key));
 69             }
 70             // 定义 BufferedReader输入流来读取URL的响应
 71             in = new BufferedReader(new InputStreamReader(
 72                     connection.getInputStream(),"utf-8"));//防止乱码
 73             String line;
 74             while ((line = in.readLine()) != null) {
 75                 result += line;
 76             }
 77         } catch (Exception e) {
 78             System.out.println("发送GET请求出现异常!" + e);
 79             e.printStackTrace();
 80         }
 81         // 使用finally块来关闭输入流
 82         finally {
 83             try {
 84                 if (in != null) {
 85                     in.close();
 86                 }
 87             } catch (Exception e2) {
 88                 e2.printStackTrace();
 89             }
 90         }
 91         return result;
 92     }
 93     public static String doPost(String url,Map<String,String> map) {
 94         String body = null;
 95         HttpEntity entity = null;
 96         System.out.println(url);
 97         try {
 98             @SuppressWarnings("resource")
 99             HttpClient httpClient = new DefaultHttpClient();
100             HttpPost method = new HttpPost(url); 
101              //设置参数  
102             List<NameValuePair> list = new ArrayList<NameValuePair>();  
103             Iterator iterator = map.entrySet().iterator();  
104             while(iterator.hasNext()){  
105                 Entry<String,String> elem = (Entry<String, String>) iterator.next();  
106                 list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));  
107             }  
108             if(list.size() > 0){  
109                 UrlEncodedFormEntity entity1 = new UrlEncodedFormEntity(list,"utf-8");  
110                 method.setEntity(entity1);  
111             } 
112             HttpResponse httpresponse = httpClient.execute(method);
113             entity = httpresponse.getEntity();
114             body = EntityUtils.toString(entity);
115             if (entity != null) {
116                 entity.consumeContent();
117             }
118         } catch (Exception e) {
119             e.printStackTrace();
120         } finally {
121             if (entity != null) {
122                 try {
123                     entity.consumeContent();
124                 } catch (IOException e) {
125                     e.printStackTrace();
126                 }
127             }
128         }
129         return body;
130     }
131     /**
132      * 上传图片
133      * @param urlStr
134      * @param textMap
135      * @param fileMap
136      * @param contentType 没有传入文件类型默认采用application/octet-stream
137      * contentType非空采用filename匹配默认的图片类型
138      * @return 返回response数据
139      */
140     @SuppressWarnings("rawtypes")
141     public static String formUpload(String urlStr, Map<String, String> textMap,
142             Map<String, String> fileMap,String contentType) {
143         String res = "";
144         HttpURLConnection conn = null;
145         // boundary就是request头和上传文件内容的分隔符
146         String BOUNDARY = "---------------------------123821742118716"; 
147         try {
148             URL url = new URL(urlStr);
149             conn = (HttpURLConnection) url.openConnection();
150             conn.setConnectTimeout(5000);
151             conn.setReadTimeout(30000);
152             conn.setDoOutput(true);
153             conn.setDoInput(true);
154             conn.setUseCaches(false);
155             conn.setRequestMethod("POST");
156             conn.setRequestProperty("Connection", "Keep-Alive");
157             conn.setRequestProperty("User-Agent",
158                     "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
159             conn.setRequestProperty("Content-Type",
160                     "multipart/form-data; boundary=" + BOUNDARY);
161             OutputStream out = new DataOutputStream(conn.getOutputStream());
162             // text
163             if (textMap != null) {
164                 StringBuffer strBuf = new StringBuffer();
165                 Iterator iter = textMap.entrySet().iterator();
166                 while (iter.hasNext()) {
167                     Map.Entry entry = (Map.Entry) iter.next();
168                     String inputName = (String) entry.getKey();
169                     String inputValue = (String) entry.getValue();
170                     if (inputValue == null) {
171                         continue;
172                     }
173                     strBuf.append("\r\n").append("--").append(BOUNDARY)
174                             .append("\r\n");
175                     strBuf.append("Content-Disposition: form-data; name=\""
176                             + inputName + "\"\r\n\r\n");
177                     strBuf.append(inputValue);
178                 }
179                 out.write(strBuf.toString().getBytes());
180             }
181             // file
182             if (fileMap != null) {
183                 Iterator iter = fileMap.entrySet().iterator();
184                 while (iter.hasNext()) {
185                     Map.Entry entry = (Map.Entry) iter.next();
186                     String inputName = (String) entry.getKey();
187                     String inputValue = (String) entry.getValue();
188                     if (inputValue == null) {
189                         continue;
190                     }
191                     File file = new File(inputValue);
192                     String filename = file.getName();
193                     
194                     //没有传入文件类型,同时根据文件获取不到类型,默认采用application/octet-stream
195                     contentType = new MimetypesFileTypeMap().getContentType(file);
196                     //contentType非空采用filename匹配默认的图片类型
197                     if(!"".equals(contentType)){
198                         if (filename.endsWith(".png")) {
199                             contentType = "image/png"; 
200                         }else if (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || filename.endsWith(".jpe")) {
201                             contentType = "image/jpeg";
202                         }else if (filename.endsWith(".gif")) {
203                             contentType = "image/gif";
204                         }else if (filename.endsWith(".ico")) {
205                             contentType = "image/image/x-icon";
206                         }
207                     }
208                     if (contentType == null || "".equals(contentType)) {
209                         contentType = "application/octet-stream";
210                     }
211                     StringBuffer strBuf = new StringBuffer();
212                     strBuf.append("\r\n").append("--").append(BOUNDARY)
213                             .append("\r\n");
214                     strBuf.append("Content-Disposition: form-data; name=\""
215                             + inputName + "\"; filename=\"" + filename
216                             + "\"\r\n");
217                     strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
218                     out.write(strBuf.toString().getBytes());
219                     DataInputStream in = new DataInputStream(
220                             new FileInputStream(file));
221                     int bytes = 0;
222                     byte[] bufferOut = new byte[1024];
223                     while ((bytes = in.read(bufferOut)) != -1) {
224                         out.write(bufferOut, 0, bytes);
225                     }
226                     in.close();
227                 }
228             }
229             byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
230             out.write(endData);
231             out.flush();
232             out.close();
233             // 读取返回数据
234             StringBuffer strBuf = new StringBuffer();
235             BufferedReader reader = new BufferedReader(new InputStreamReader(
236                     conn.getInputStream()));
237             String line = null;
238             while ((line = reader.readLine()) != null) {
239                 strBuf.append(line).append("\n");
240             }
241             res = strBuf.toString();
242             reader.close();
243             reader = null;
244         } catch (Exception e) {
245             System.out.println("发送POST请求出错。" + urlStr);
246             e.printStackTrace();
247         } finally {
248             if (conn != null) {
249                 conn.disconnect();
250                 conn = null;
251             }
252         }
253         return res;
254     }
255     public static String httpPostRequest(String url, String postContent) throws Exception{  
256         OutputStream outputstream = null;  
257         BufferedReader in = null;  
258         try  
259         {  
260             URL url2 = new URL(url);
261             URLConnection httpurlconnection = url2.openConnection();  
262             httpurlconnection.setConnectTimeout(10 * 1000);  
263             httpurlconnection.setDoOutput(true);  
264             httpurlconnection.setUseCaches(false);  
265             OutputStreamWriter out = new OutputStreamWriter(httpurlconnection  
266                     .getOutputStream(), "UTF-8");  
267             out.write(postContent);  
268             out.flush();  
269               
270             StringBuffer result = new StringBuffer();  
271             in = new BufferedReader(new InputStreamReader(httpurlconnection  
272                     .getInputStream(),"UTF-8"));  
273             String line;  
274             while ((line = in.readLine()) != null)  
275             {  
276                 result.append(line);  
277             }  
278             return result.toString();  
279         }  
280         catch(Exception ex){  
281             throw new Exception("post请求异常:" + ex.getMessage());  
282         }  
283         finally  
284         {  
285             if (outputstream != null)  
286             {  
287                 try  
288                 {  
289                     outputstream.close();  
290                 }  
291                 catch (IOException e)  
292                 {  
293                     outputstream = null;  
294                 }  
295             }  
296             if (in != null)  
297             {  
298                 try  
299                 {  
300                     in.close();  
301                 }  
302                 catch (IOException e)  
303                 {  
304                     in = null;  
305                 }  
306             }  
307         }     
308     } 
309     /**
310      * 测试上传png图片
311      * 
312      */
313     public static void testUploadImage(){
314         String url = "http://10.4.253.41/PTYUN1.2/extLogin/test.do";
315         String fileName = "E:/test/ts.png";
316         Map<String, String> textMap = new HashMap<String, String>();
317         //可以设置多个input的name,value
318         textMap.put("name", "testname");
319         textMap.put("type", "2");
320         //设置file的name,路径
321         Map<String, String> fileMap = new HashMap<String, String>();
322         fileMap.put("upfile", fileName);
323         String contentType = "";//image/png
324         String ret = formUpload(url, textMap, fileMap,contentType);
325         System.out.println(ret);
326         //{"status":"0","message":"add succeed","baking_url":"group1\/M00\/00\/A8\/CgACJ1Zo-LuAN207AAQA3nlGY5k151.png"}
327     }
328     public static void main(String[] args) throws Exception {
329 //          Map<String,String> createMap = new HashMap<String,String>();
330 //          
331 //          createMap.put("authuser","*****");  
332 //          createMap.put("authpass","*****");  
333 //          createMap.put("orgkey","****");  
334 //          createMap.put("orgname","yonghuming");  
335 //          String result = HttpXmlClient.doPost("http://10.4.253.41/PTYUN1.2/extLogin/extEdit.do",createMap);
336 //          System.out.println(result);
337         testUploadImage();
338     }
339 }

 

httpClient工具类

标签:imp   mozilla   size   根据   exe   sum   new   多个   method   

原文地址:http://www.cnblogs.com/dp-blog/p/7463895.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!