【Android学习】http协议编程的三种方式

来源:互联网 发布:用于有序数据相合性 编辑:程序博客网 时间:2024/04/30 00:29

一、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方式

import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.HashMap;import java.util.Map;public class http_get1 {// public static final String path =// "http://192.168.137.103:8080/MyHttp/servlet/LoginAction";public static final String path = "http://localhost:8080/MyHttp/servlet/LoginAction";public static String getStringFromStream(InputStream is) {String str = "";ByteArrayOutputStream bos = new ByteArrayOutputStream();int len = 0;byte[] data = new byte[1024];if(is!=null){try {while ((len = is.read(data)) != -1) {bos.write(data, 0, len);}str = new String(bos.toByteArray(), "utf-8");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return str;}public static InputStream useGetMethod(Map<String, String> map,String encode) {InputStream is = null;StringBuffer sb = new StringBuffer(path);sb.append("?");if (map != null && !map.isEmpty()) {for (Map.Entry<String, String> entry : map.entrySet()) {sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");}sb.deleteCharAt(sb.length() - 1);System.out.println(sb.toString());URL url = null;OutputStream os = null;try {url = new URL(sb.toString());if (url != null) {HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setRequestMethod("GET");con.setConnectTimeout(3000);con.setDoInput(true);con.setDoOutput(true);os = con.getOutputStream();os.write(sb.toString().getBytes(encode));os.close();if (con.getResponseCode() == 200) {is = con.getInputStream();}}} catch (Exception e) {}}return is;}public static void main(String[] args) {// TODO Auto-generated method stubMap<String, String> map = new HashMap<String, String>();map.put("username", "admin");map.put("password", "1243");String str = getStringFromStream(useGetMethod(map, "utf-8"));System.out.println(str);}}

2、POST方式

import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.HashMap;import java.util.Map;public class http_post1 {// 使用POST请求与GET请求的区别就是POST请求不需要封装请求路径,只需要封装请求参数public static InputStream usePostMethod(Map<String, String> map,String encode) {StringBuffer buffer = new StringBuffer();InputStream is = null;OutputStream os = null;if (map != null && !map.isEmpty()) {for (Map.Entry<String, String> entry : map.entrySet()) {try {buffer.append(entry.getKey()).append("=").append(entry.getValue())// .append(URLEncoder.encode(entry.getValue(),// encode)).append("&");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}buffer.deleteCharAt(buffer.length() - 1);System.out.println(buffer.toString());}try {URL url = new URL(http_get1.path);if (url != null) {HttpURLConnection con = (HttpURLConnection) url.openConnection();con.setDoInput(true);con.setDoOutput(true);con.setRequestMethod("POST");con.setConnectTimeout(3000);byte[] tdata = buffer.toString().getBytes();// con.setRequestProperty("Content-Type",// "application/x-www-form-urlencoded");// con.setRequestProperty("Content-Length",// String.valueOf(tdata.length));os = con.getOutputStream();os.write(tdata);os.close();if (con.getResponseCode() == 200) {is = con.getInputStream();}}} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return is;}public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("username", "admin");map.put("password", "123");System.out.println(http_get1.getStringFromStream(usePostMethod(map,"utf-8")));}}



四、Apache接口

import java.io.InputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.http.HttpResponse;import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;public class http_myapache {public static InputStream useApacheMethod(Map<String, String> map,String encode) {InputStream is = null;List<NameValuePair> list = new ArrayList<NameValuePair>();for (Map.Entry<String, String> entry : map.entrySet()) {list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));}try {// 封装请求参数UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);// 设置请求参数HttpPost post = new HttpPost(http_get1.path);post.setEntity(entity);// 执行请求DefaultHttpClient client = new DefaultHttpClient();HttpResponse response = client.execute(post);// 获取状态码if (response.getStatusLine().getStatusCode() == 200) {is = response.getEntity().getContent();}} catch (Exception e) {// TODO: handle exception}return is;}public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("username", "admin");map.put("password", "123");System.out.println(http_get1.getStringFromStream(useApacheMethod(map,"utf-8")));}}


总结

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

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

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

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



0 0
原创粉丝点击