HTTP之java实例

来源:互联网 发布:北汽黄骅分公司 知乎 编辑:程序博客网 时间:2024/06/06 03:07

一、POST与GET的区别:

1、GET是从服务器上获取数据,POST是向服务器传送数据。
2、在客户端, GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在HTML HEADER内提交。
3、对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数。
4、GET方式提交的数据最多只能有1024字节,而POST则没有此限制。
5、安全性问题。正如在(2)中提到,使用 GET 的时候,参数会显示在地址栏上,而 POST 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用 GET ;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 POST为好。

二、Java中的Http编程主要有两种

1、标准的Java接口

2、标准的Apache接口

三、标准的Java接口编程

1、GET方式

[java] view plain copy
print?
  1. import java.io.ByteArrayOutputStream;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.OutputStream;  
  5. import java.net.HttpURLConnection;  
  6. import java.net.URL;  
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.   
  10.   
  11. public class http_get1 {  
  12.   
  13.   
  14.     // public static final String path =  
  15.     // "http://192.168.137.103:8080/MyHttp/servlet/LoginAction";  
  16.     public static final String path = "http://localhost:8080/MyHttp/servlet/LoginAction";  
  17.   
  18.   
  19.     public static String getStringFromStream(InputStream is) {  
  20.         String str = "";  
  21.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  22.         int len = 0;  
  23.         byte[] data = new byte[1024];  
  24.         if(is!=null){  
  25.             try {  
  26.                 while ((len = is.read(data)) != -1) {  
  27.                     bos.write(data, 0, len);  
  28.                 }  
  29.   
  30.   
  31.                 str = new String(bos.toByteArray(), "utf-8");  
  32.             } catch (IOException e) {  
  33.                 // TODO Auto-generated catch block  
  34.                 e.printStackTrace();  
  35.             }  
  36.   
  37.   
  38.         }  
  39.           
  40.         return str;  
  41.     }  
  42.   
  43.   
  44.     public static InputStream useGetMethod(Map<String, String> map,  
  45.             String encode) {  
  46.         InputStream is = null;  
  47.         StringBuffer sb = new StringBuffer(path);  
  48.         sb.append("?");  
  49.         if (map != null && !map.isEmpty()) {  
  50.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  51.                 sb.append(entry.getKey()).append("=").append(entry.getValue())  
  52.                         .append("&");  
  53.             }  
  54.             sb.deleteCharAt(sb.length() - 1);  
  55.             System.out.println(sb.toString());  
  56.             URL url = null;  
  57.   
  58.   
  59.             OutputStream os = null;  
  60.             try {  
  61.                 url = new URL(sb.toString());  
  62.                 if (url != null) {  
  63.                     HttpURLConnection con = (HttpURLConnection) url  
  64.                             .openConnection();  
  65.                     con.setRequestMethod("GET");  
  66.                     con.setConnectTimeout(3000);  
  67.                     con.setDoInput(true);  
  68.                     con.setDoOutput(true);  
  69.                     os = con.getOutputStream();  
  70.                     os.write(sb.toString().getBytes(encode));  
  71.                     os.close();  
  72.                     if (con.getResponseCode() == 200) {  
  73.                         is = con.getInputStream();  
  74.                     }  
  75.                 }  
  76.   
  77.   
  78.             } catch (Exception e) {  
  79.   
  80.   
  81.             }  
  82.   
  83.   
  84.         }  
  85.   
  86.   
  87.         return is;  
  88.     }  
  89.   
  90.   
  91.     public static void main(String[] args) {  
  92.         // TODO Auto-generated method stub  
  93.   
  94.   
  95.         Map<String, String> map = new HashMap<String, String>();  
  96.         map.put("username""admin");  
  97.         map.put("password""1243");  
  98.         String str = getStringFromStream(useGetMethod(map, "utf-8"));  
  99.         System.out.println(str);  
  100.     }  
  101.   
  102.   
  103. }  

2、POST方式

[java] view plain copy
print?
  1. import java.io.IOException;  
  2. import java.io.InputStream;  
  3. import java.io.OutputStream;  
  4. import java.net.HttpURLConnection;  
  5. import java.net.MalformedURLException;  
  6. import java.net.URL;  
  7. import java.util.HashMap;  
  8. import java.util.Map;  
  9.   
  10.   
  11. public class http_post1 {  
  12.   
  13.   
  14.     // 使用POST请求与GET请求的区别就是POST请求不需要封装请求路径,只需要封装请求参数  
  15.     public static InputStream usePostMethod(Map<String, String> map,  
  16.             String encode) {  
  17.         StringBuffer buffer = new StringBuffer();  
  18.         InputStream is = null;  
  19.         OutputStream os = null;  
  20.         if (map != null && !map.isEmpty()) {  
  21.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  22.                 try {  
  23.                     buffer.append(entry.getKey()).append("=")  
  24.                             .append(entry.getValue())  
  25.                             // .append(URLEncoder.encode(entry.getValue(),  
  26.                             // encode))  
  27.                             .append("&");  
  28.                 } catch (Exception e) {  
  29.                     // TODO Auto-generated catch block  
  30.                     e.printStackTrace();  
  31.                 }  
  32.             }  
  33.             buffer.deleteCharAt(buffer.length() - 1);  
  34.             System.out.println(buffer.toString());  
  35.         }  
  36.         try {  
  37.             URL url = new URL(http_get1.path);  
  38.             if (url != null) {  
  39.                 HttpURLConnection con = (HttpURLConnection) url  
  40.                         .openConnection();  
  41.                 con.setDoInput(true);  
  42.                 con.setDoOutput(true);  
  43.                 con.setRequestMethod("POST");  
  44.                 con.setConnectTimeout(3000);  
  45.                 byte[] tdata = buffer.toString().getBytes();  
  46.   
  47.   
  48.                 // con.setRequestProperty("Content-Type",  
  49.                 // "application/x-www-form-urlencoded");  
  50.                 // con.setRequestProperty("Content-Length",  
  51.                 // String.valueOf(tdata.length));  
  52.   
  53.   
  54.                 os = con.getOutputStream();  
  55.                 os.write(tdata);  
  56.                 os.close();  
  57.                 if (con.getResponseCode() == 200) {  
  58.   
  59.   
  60.                     is = con.getInputStream();  
  61.                 }  
  62.   
  63.   
  64.             }  
  65.   
  66.   
  67.         } catch (MalformedURLException e) {  
  68.             // TODO Auto-generated catch block  
  69.             e.printStackTrace();  
  70.         } catch (IOException e) {  
  71.             // TODO Auto-generated catch block  
  72.             e.printStackTrace();  
  73.         }  
  74.   
  75.   
  76.         return is;  
  77.     }  
  78.   
  79.   
  80.     public static void main(String[] args) {  
  81.   
  82.   
  83.         Map<String, String> map = new HashMap<String, String>();  
  84.         map.put("username""admin");  
  85.         map.put("password""123");  
  86.         System.out.println(http_get1.getStringFromStream(usePostMethod(map,  
  87.                 "utf-8")));  
  88.   
  89.   
  90.     }  
  91.   
  92.   
  93. }  



四、Apache接口

[java] view plain copy
print?
  1. import java.io.InputStream;  
  2. import java.util.ArrayList;  
  3. import java.util.HashMap;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7.   
  8. import org.apache.http.HttpResponse;  
  9. import org.apache.http.NameValuePair;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.message.BasicNameValuePair;  
  14.   
  15.   
  16. public class http_myapache {  
  17.   
  18.   
  19.     public static InputStream useApacheMethod(Map<String, String> map,  
  20.             String encode) {  
  21.         InputStream is = null;  
  22.         List<NameValuePair> list = new ArrayList<NameValuePair>();  
  23.   
  24.   
  25.         for (Map.Entry<String, String> entry : map.entrySet()) {  
  26.             list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
  27.   
  28.   
  29.         }  
  30.         try {  
  31.             // 封装请求参数  
  32.             UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);  
  33.             // 设置请求参数  
  34.             HttpPost post = new HttpPost(http_get1.path);  
  35.             post.setEntity(entity);  
  36.             // 执行请求  
  37.             DefaultHttpClient client = new DefaultHttpClient();  
  38.             HttpResponse response = client.execute(post);  
  39.             // 获取状态码  
  40.             if (response.getStatusLine().getStatusCode() == 200) {  
  41.                 is = response.getEntity().getContent();  
  42.             }  
  43.   
  44.   
  45.         } catch (Exception e) {  
  46.             // TODO: handle exception  
  47.         }  
  48.   
  49.   
  50.         return is;  
  51.   
  52.   
  53.     }  
  54.   
  55.   
  56.     public static void main(String[] args) {  
  57.   
  58.   
  59.         Map<String, String> map = new HashMap<String, String>();  
  60.         map.put("username""admin");  
  61.         map.put("password""123");  
  62.         System.out.println(http_get1.getStringFromStream(useApacheMethod(map,  
  63.                 "utf-8")));  
  64.     }  
  65.   
  66.   
  67. }  


总结

对于普通的Http编程可以选择GET方式或者POST方式,但对于更高要求的HTTP编程,Apache提供 的标准接口则更为灵活。

附Apache编程的JAR包和XMLPull解析时用到的JAR包:

Apache编程时用到的JAR包:
点击打开链接

XMLPull解析时用到的JAR包:
点击打开链接

原创粉丝点击