HttpURLConnection的get和post处理方法(含图片)

来源:互联网 发布:js 添加div classname 编辑:程序博客网 时间:2024/05/22 04:24

原文地址http://blog.csdn.net/arsenic/article/details/8120581

通用方法GET和POST

[java] view plaincop
  1. package com.dong.test.binaryimage;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.ByteArrayOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.InputStreamReader;  
  8. import java.io.OutputStream;  
  9. import java.io.UnsupportedEncodingException;  
  10. import java.net.HttpURLConnection;  
  11. import java.net.MalformedURLException;  
  12. import java.net.URL;  
  13. import java.net.URLConnection;  
  14. import java.net.URLEncoder;  
  15. import java.util.HashMap;  
  16. import java.util.List;  
  17. import java.util.Map;  
  18.   
  19. public class TestHttpPost {  
  20.   
  21.     private static String PATH = "http://localhost:8080/TestWeb/servlet/HelloServer";  
  22.     private static URL url;  
  23.   
  24.     public TestHttpPost() {  
  25.         // TODO Auto-generated constructor stub  
  26.     }  
  27.   
  28.     static {  
  29.         try {  
  30.             url = new URL(PATH);  
  31.         } catch (MalformedURLException e) {  
  32.             // TODO Auto-generated catch block  
  33.             e.printStackTrace();  
  34.         }  
  35.     }  
  36.   
  37.     /** 
  38.      * @param args 
  39.      */  
  40.     public static void main(String[] args) {  
  41.         Map<String, String> map = new HashMap<String, String>();  
  42.         map.put("name""xiaowang");  
  43.         map.put("age""29");  
  44.   
  45.         System.out.println(sendPostMessage(map, "UTF-8"));  
  46.         System.out.println(sendGet(PATH,"name=xiaowang"));  
  47.     }  
  48.   
  49.     public static String sendGet(String url, String param)  
  50.   
  51.     {  
  52.   
  53.         String result = "";  
  54.   
  55.         BufferedReader in = null;  
  56.   
  57.         try  
  58.   
  59.         {  
  60.   
  61.             String urlName = url + "?" + param;  
  62.   
  63.             URL realUrl = new URL(urlName);  
  64.   
  65.             // 打开和URL之间的连接  
  66.   
  67.             URLConnection conn = realUrl.openConnection();  
  68.   
  69.             // 设置通用的请求属性  
  70.   
  71.             conn.setRequestProperty("accept""*/*");  
  72.   
  73.             conn.setRequestProperty("connection""Keep-Alive");  
  74.   
  75.             conn.setRequestProperty("user-agent",  
  76.   
  77.             "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
  78.   
  79.             // 建立实际的连接  
  80.   
  81.             conn.connect();  
  82.   
  83.             // 获取所有响应头字段  
  84.   
  85.             Map<String, List<String>> map = conn.getHeaderFields();  
  86.   
  87.             // 遍历所有的响应头字段  
  88.   
  89.             for (String key : map.keySet())  
  90.   
  91.             {  
  92.   
  93.                 System.out.println(key + "--->" + map.get(key));  
  94.   
  95.             }  
  96.   
  97.             // 定义BufferedReader输入流来读取URL的响应  
  98.   
  99.             in = new BufferedReader(  
  100.                     new InputStreamReader(conn.getInputStream()));  
  101.   
  102.             String line;  
  103.   
  104.             while ((line = in.readLine()) != null)  
  105.   
  106.             {  
  107.   
  108.                 result += "\n" + line;  
  109.   
  110.             }  
  111.   
  112.         }  
  113.   
  114.         catch (Exception e)  
  115.   
  116.         {  
  117.   
  118.             System.out.println("发送GET请求出现异常!" + e);  
  119.   
  120.             e.printStackTrace();  
  121.   
  122.         }  
  123.   
  124.         // 使用finally块来关闭输入流  
  125.   
  126.         finally  
  127.   
  128.         {  
  129.   
  130.             try  
  131.   
  132.             {  
  133.   
  134.                 if (in != null)  
  135.   
  136.                 {  
  137.   
  138.                     in.close();  
  139.   
  140.                 }  
  141.   
  142.             }  
  143.   
  144.             catch (IOException ex)  
  145.   
  146.             {  
  147.   
  148.                 ex.printStackTrace();  
  149.   
  150.             }  
  151.   
  152.         }  
  153.   
  154.         return result;  
  155.   
  156.     }  
  157.   
  158.     public static String sendPostMessage(Map<String, String> params,  
  159.             String encode) {  
  160.         // 作为StringBuffer初始化的字符串  
  161.         StringBuffer buffer = new StringBuffer();  
  162.         try {  
  163.             if (params != null && !params.isEmpty()) {  
  164.                 for (Map.Entry<String, String> entry : params.entrySet()) {  
  165.                     // 完成转码操作  
  166.                     buffer.append(entry.getKey()).append("=").append(  
  167.                             URLEncoder.encode(entry.getValue(), encode))  
  168.                             .append("&");  
  169.                 }  
  170.                 buffer.deleteCharAt(buffer.length() - 1);  
  171.             }  
  172.             // System.out.println(buffer.toString());  
  173.             // 删除掉最有一个&  
  174.   
  175.             System.out.println("-->>" + buffer.toString());  
  176.             HttpURLConnection urlConnection = (HttpURLConnection) url  
  177.                     .openConnection();  
  178.             urlConnection.setConnectTimeout(3000);  
  179.             urlConnection.setRequestMethod("POST");  
  180.             urlConnection.setDoInput(true);// 表示从服务器获取数据  
  181.             urlConnection.setDoOutput(true);// 表示向服务器写数据  
  182.             // 获得上传信息的字节大小以及长度  
  183.             byte[] mydata = buffer.toString().getBytes();  
  184.             // 表示设置请求体的类型是文本类型  
  185.             urlConnection.setRequestProperty("Content-Type",  
  186.                     "application/x-www-form-urlencoded");  
  187.             urlConnection.setRequestProperty("Content-Length", String  
  188.                     .valueOf(mydata.length));  
  189.             // 获得输出流,向服务器输出数据  
  190.             OutputStream outputStream = urlConnection.getOutputStream();  
  191.             outputStream.write(mydata, 0, mydata.length);  
  192.             outputStream.close();  
  193.             // 获得服务器响应的结果和状态码  
  194.             int responseCode = urlConnection.getResponseCode();  
  195.             if (responseCode == 200) {  
  196.                 return changeInputStream(urlConnection.getInputStream(), encode);  
  197.             }  
  198.         } catch (UnsupportedEncodingException e) {  
  199.             // TODO Auto-generated catch block  
  200.             e.printStackTrace();  
  201.         } catch (IOException e) {  
  202.             // TODO Auto-generated catch block  
  203.             e.printStackTrace();  
  204.         }  
  205.         return "";  
  206.     }  
  207.   
  208.     private static String changeInputStream(InputStream inputStream,  
  209.             String encode) {  
  210.         // TODO Auto-generated method stub  
  211.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
  212.         byte[] data = new byte[1024];  
  213.         int len = 0;  
  214.         String result = "";  
  215.         if (inputStream != null) {  
  216.             try {  
  217.                 while ((len = inputStream.read(data)) != -1) {  
  218.                     outputStream.write(data, 0, len);  
  219.                 }  
  220.                 result = new String(outputStream.toByteArray(), encode);  
  221.             } catch (IOException e) {  
  222.                 // TODO Auto-generated catch block  
  223.                 e.printStackTrace();  
  224.             }  
  225.         }  
  226.         return result;  
  227.     }  
  228.   
  229. }  


 

 


GET处理方法

[java] view plaincopy
  1. package com.http.get;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.net.HttpURLConnection;  
  7. import java.net.MalformedURLException;  
  8. import java.net.URL;  
  9.   
  10. import org.apache.http.message.BasicNameValuePair;  
  11.   
  12. public class HttpUtils {  
  13.   
  14.     private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png";  
  15.   
  16.     public HttpUtils() {  
  17.         // TODO Auto-generated constructor stub  
  18.     }  
  19.   
  20.     public static void saveImageToDisk() {  
  21.         InputStream inputStream = getInputStream();  
  22.         byte[] data = new byte[1024];  
  23.         int len = 0;  
  24.         FileOutputStream fileOutputStream = null;  
  25.         try {  
  26.             fileOutputStream = new FileOutputStream("C:\\test.png");  
  27.             while ((len = inputStream.read(data)) != -1) {  
  28.                 fileOutputStream.write(data, 0, len);  
  29.             }  
  30.         } catch (IOException e) {  
  31.             // TODO Auto-generated catch block  
  32.             e.printStackTrace();  
  33.         } finally {  
  34.             if (inputStream != null) {  
  35.                 try {  
  36.                     inputStream.close();  
  37.                 } catch (IOException e) {  
  38.                     // TODO Auto-generated catch block  
  39.                     e.printStackTrace();  
  40.                 }  
  41.             }  
  42.             if (fileOutputStream != null) {  
  43.                 try {  
  44.                     fileOutputStream.close();  
  45.                 } catch (IOException e) {  
  46.                     // TODO Auto-generated catch block  
  47.                     e.printStackTrace();  
  48.                 }  
  49.             }  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * 获得服务器端的数据,以InputStream形式返回 
  55.      * @return 
  56.      */  
  57.     public static InputStream getInputStream() {  
  58.         InputStream inputStream = null;  
  59.         HttpURLConnection httpURLConnection = null;  
  60.         try {  
  61.             URL url = new URL(URL_PATH);  
  62.             if (url != null) {  
  63.                 httpURLConnection = (HttpURLConnection) url.openConnection();  
  64.                 // 设置连接网络的超时时间  
  65.                 httpURLConnection.setConnectTimeout(3000);  
  66.                 httpURLConnection.setDoInput(true);  
  67.                 // 表示设置本次http请求使用GET方式请求  
  68.                 httpURLConnection.setRequestMethod("GET");  
  69.                 int responseCode = httpURLConnection.getResponseCode();  
  70.                 if (responseCode == 200) {  
  71.                     // 从服务器获得一个输入流  
  72.                     inputStream = httpURLConnection.getInputStream();  
  73.                 }  
  74.             }  
  75.         } catch (MalformedURLException e) {  
  76.             // TODO Auto-generated catch block  
  77.             e.printStackTrace();  
  78.         } catch (IOException e) {  
  79.             // TODO Auto-generated catch block  
  80.             e.printStackTrace();  
  81.         }  
  82.         return inputStream;  
  83.     }  
  84.   
  85.     public static void main(String[] args) {  
  86.         // 从服务器获得图片保存到本地  
  87.         saveImageToDisk();  
  88.     }  
  89. }  


POST

[java] view plaincopy
  1. package com.http.post;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.net.HttpURLConnection;  
  9. import java.net.MalformedURLException;  
  10. import java.net.URL;  
  11. import java.net.URLEncoder;  
  12. import java.util.HashMap;  
  13. import java.util.Map;  
  14.   
  15. public class HttpUtils {  
  16.   
  17.     // 请求服务器端的url  
  18.     private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";  
  19.     private static URL url;  
  20.   
  21.     public HttpUtils() {  
  22.         // TODO Auto-generated constructor stub  
  23.     }  
  24.   
  25.     static {  
  26.         try {  
  27.             url = new URL(PATH);  
  28.         } catch (MalformedURLException e) {  
  29.             // TODO Auto-generated catch block  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33.   
  34.     /** 
  35.      * @param params 
  36.      *            填写的url的参数 
  37.      * @param encode 
  38.      *            字节编码 
  39.      * @return 
  40.      */  
  41.     public static String sendPostMessage(Map<String, String> params,  
  42.             String encode) {  
  43.         // 作为StringBuffer初始化的字符串  
  44.         StringBuffer buffer = new StringBuffer();  
  45.         try {  
  46.             if (params != null && !params.isEmpty()) {  
  47.                   for (Map.Entry<String, String> entry : params.entrySet()) {  
  48.                         // 完成转码操作  
  49.                         buffer.append(entry.getKey()).append("=").append(  
  50.                                 URLEncoder.encode(entry.getValue(), encode))  
  51.                                 .append("&");  
  52.                     }  
  53.                 buffer.deleteCharAt(buffer.length() - 1);  
  54.             }  
  55.             // System.out.println(buffer.toString());  
  56.             // 删除掉最有一个&  
  57.               
  58.             System.out.println("-->>"+buffer.toString());  
  59.             HttpURLConnection urlConnection = (HttpURLConnection) url  
  60.                     .openConnection();  
  61.             urlConnection.setConnectTimeout(3000);  
  62.             urlConnection.setRequestMethod("POST");  
  63.             urlConnection.setDoInput(true);// 表示从服务器获取数据  
  64.             urlConnection.setDoOutput(true);// 表示向服务器写数据  
  65.             // 获得上传信息的字节大小以及长度  
  66.             byte[] mydata = buffer.toString().getBytes();  
  67.             // 表示设置请求体的类型是文本类型  
  68.             urlConnection.setRequestProperty("Content-Type",  
  69.                     "application/x-www-form-urlencoded");  
  70.             urlConnection.setRequestProperty("Content-Length",  
  71.                     String.valueOf(mydata.length));  
  72.             // 获得输出流,向服务器输出数据  
  73.             OutputStream outputStream = urlConnection.getOutputStream();  
  74.             outputStream.write(mydata,0,mydata.length);  
  75.             outputStream.close();  
  76.             // 获得服务器响应的结果和状态码  
  77.             int responseCode = urlConnection.getResponseCode();  
  78.             if (responseCode == 200) {  
  79.                 return changeInputStream(urlConnection.getInputStream(), encode);  
  80.             }  
  81.         } catch (UnsupportedEncodingException e) {  
  82.             // TODO Auto-generated catch block  
  83.             e.printStackTrace();  
  84.         } catch (IOException e) {  
  85.             // TODO Auto-generated catch block  
  86.             e.printStackTrace();  
  87.         }  
  88.         return "";  
  89.     }  
  90.   
  91.     /** 
  92.      * 将一个输入流转换成指定编码的字符串 
  93.      *  
  94.      * @param inputStream 
  95.      * @param encode 
  96.      * @return 
  97.      */  
  98.     private static String changeInputStream(InputStream inputStream,  
  99.             String encode) {  
  100.         // TODO Auto-generated method stub  
  101.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
  102.         byte[] data = new byte[1024];  
  103.         int len = 0;  
  104.         String result = "";  
  105.         if (inputStream != null) {  
  106.             try {  
  107.                 while ((len = inputStream.read(data)) != -1) {  
  108.                     outputStream.write(data, 0, len);  
  109.                 }  
  110.                 result = new String(outputStream.toByteArray(), encode);  
  111.             } catch (IOException e) {  
  112.                 // TODO Auto-generated catch block  
  113.                 e.printStackTrace();  
  114.             }  
  115.         }  
  116.         return result;  
  117.     }  
  118.   
  119.     /** 
  120.      * @param args 
  121.      */  
  122.     public static void main(String[] args) {  
  123.         // TODO Auto-generated method stub  
  124.         Map<String, String> params = new HashMap<String, String>();  
  125.         params.put("username""admin");  
  126.         params.put("password""1234");  
  127.         String result = HttpUtils.sendPostMessage(params, "utf-8");  
  128.         System.out.println("--result->>" + result);  
  129.     }  
  130.   
  131. }  


 

[java] view plaincopy
  1. package com.http.post;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import org.apache.http.HttpResponse;  
  13. import org.apache.http.NameValuePair;  
  14. import org.apache.http.client.ClientProtocolException;  
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  16. import org.apache.http.client.methods.HttpPost;  
  17. import org.apache.http.impl.client.DefaultHttpClient;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19.   
  20. public class HttpUtils {  
  21.   
  22.     public HttpUtils() {  
  23.         // TODO Auto-generated constructor stub  
  24.     }  
  25.   
  26.     public static String sendHttpClientPost(String path,  
  27.             Map<String, String> map, String encode) {  
  28.         List<NameValuePair> list = new ArrayList<NameValuePair>();  
  29.         if (map != null && !map.isEmpty()) {  
  30.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  31.                 list.add(new BasicNameValuePair(entry.getKey(), entry  
  32.                         .getValue()));  
  33.             }  
  34.         }  
  35.         try {  
  36.             // 实现将请求的参数封装到表单中,请求体重  
  37.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);  
  38.             // 使用Post方式提交数据  
  39.             HttpPost httpPost = new HttpPost(path);  
  40.             httpPost.setEntity(entity);  
  41.             // 指定post请求  
  42.             DefaultHttpClient client = new DefaultHttpClient();  
  43.             HttpResponse httpResponse = client.execute(httpPost);  
  44.             if (httpResponse.getStatusLine().getStatusCode() == 200) {  
  45.                 return changeInputStream(httpResponse.getEntity().getContent(),  
  46.                         encode);  
  47.             }  
  48.         } catch (UnsupportedEncodingException e) {  
  49.             // TODO Auto-generated catch block  
  50.             e.printStackTrace();  
  51.         } catch (ClientProtocolException e) {  
  52.             // TODO Auto-generated catch block  
  53.             e.printStackTrace();  
  54.         } catch (IOException e) {  
  55.             // TODO Auto-generated catch block  
  56.             e.printStackTrace();  
  57.         }  
  58.         return "";  
  59.     }  
  60.   
  61.     /** 
  62.      * 将一个输入流转换成指定编码的字符串 
  63.      *  
  64.      * @param inputStream 
  65.      * @param encode 
  66.      * @return 
  67.      */  
  68.     public static String changeInputStream(InputStream inputStream,  
  69.             String encode) {  
  70.         // TODO Auto-generated method stub  
  71.         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();  
  72.         byte[] data = new byte[1024];  
  73.         int len = 0;  
  74.         String result = "";  
  75.         if (inputStream != null) {  
  76.             try {  
  77.                 while ((len = inputStream.read(data)) != -1) {  
  78.                     outputStream.write(data, 0, len);  
  79.                 }  
  80.                 result = new String(outputStream.toByteArray(), encode);  
  81.             } catch (IOException e) {  
  82.                 // TODO Auto-generated catch block  
  83.                 e.printStackTrace();  
  84.             }  
  85.         }  
  86.         return result;  
  87.     }  
  88.   
  89.     /** 
  90.      * @param args 
  91.      */  
  92.     public static void main(String[] args) {  
  93.         // TODO Auto-generated method stub  
  94.         String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";  
  95.         Map<String, String> params = new HashMap<String, String>();  
  96.         params.put("username""admin");  
  97.         params.put("password""123");  
  98.         String result = HttpUtils.sendHttpClientPost(path, params, "utf-8");  
  99.         System.out.println("-->>"+result);  
  100.     }  
  101.   
  102. }  

0 0
原创粉丝点击