Android发送GET和POST以及HttpClient发送POST请求给服务器响应

Android GET/POST请求及HttpClient POST实践
本文介绍如何在Android应用中实现GET和POST请求,以及使用HttpClient进行POST请求,通过示例展示了请求过程,并提及服务器端的ManageServlet处理请求,同时讨论了编码问题的过滤器解决方案。

Android发送GET和POST以及HttpClient发送POST请求给服务器响应

效果如下图所示:

Android发送GET和POST以及HttpClient发送POST请求给服务器响应

 

布局main.xml

01 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:orientation="vertical"
04     android:layout_width="fill_parent"
05     android:layout_height="fill_parent"
06     >
07     <TextView 
08     android:layout_width="fill_parent"
09     android:layout_height="wrap_content"
10     android:text="@string/title"
11     />
12     <EditText 
13     android:layout_width="fill_parent"
14     android:layout_height="wrap_content"
15     android:id="@+id/title"
16     />
17      
18     <TextView 
19     android:layout_width="fill_parent"
20     android:layout_height="wrap_content"
21     android:numeric="integer"
22     android:text="@string/timelength"
23     />
24     <EditText 
25     android:layout_width="fill_parent"
26     android:layout_height="wrap_content"
27     android:id="@+id/timelength"
28     />
29     <Button android:layout_width="fill_parent"
30     android:layout_height="wrap_content"
31     android:text="@string/button"
32     android:onClick="save"
33     android:id="@+id/button"/>
34 </LinearLayout>

 

string.xml

01 <?xml version="1.0" encoding="utf-8"?>
02 <resources>
03     <string name="hello">Hello World, MainActivity!</string>
04     <string name="app_name">资讯管理</string>
05     <string name="title">标题</string>
06     <string name="timelength">时长</string>
07     <string name="button">保存</string>
08     <string name="success">保存成功</string>
09     <string name="fail">保存失败</string>
10     <string name="error">服务器响应错误</string>
11 </resources>

 

01 package cn.roco.manage;
02  
03 import cn.roco.manage.service.NewsService;
04 import android.app.Activity;
05 import android.os.Bundle;
06 import android.view.View;
07 import android.widget.EditText;
08 import android.widget.Toast;
09  
10 public class MainActivity extends Activity {
11  
12     private EditText titleText;
13     private EditText lengthText;
14  
15     /** Called when the activity is first created. */
16     @Override
17     public void onCreate(Bundle savedInstanceState) {
18         super.onCreate(savedInstanceState);
19         setContentView(R.layout.main);
20         titleText = (EditText) this.findViewById(R.id.title);
21         lengthText = (EditText) this.findViewById(R.id.timelength);
22     }
23  
24     public void save(View v) {
25         String title = titleText.getText().toString();
26         String length = lengthText.getText().toString();
27         String path = "http://192.168.1.100:8080/Hello/ManageServlet";
28         boolean result;
29         try {
30 //          result = NewsService.save(path, title, length, NewsService.GET);  //发送GET请求
31 //          result = NewsService.save(path, title, length, NewsService.POST); //发送POST请求
32             result = NewsService.save(path, title, length, NewsService.HttpClientPost); //通过HttpClient框架发送POST请求
33             if (result) {
34                 Toast.makeText(getApplicationContext(), R.string.success, 1)
35                         .show();
36             else {
37                 Toast.makeText(getApplicationContext(), R.string.fail, 1)
38                         .show();
39             }
40         catch (Exception e) {
41             Toast.makeText(getApplicationContext(), e.getMessage(), 1).show();
42             Toast.makeText(getApplicationContext(), R.string.error, 1).show();
43         }
44  
45     }
46  
47 }



 

001 package cn.roco.manage.service;
002  
003 import java.io.OutputStream;
004 import java.net.HttpURLConnection;
005 import java.net.URL;
006 import java.net.URLEncoder;
007 import java.util.ArrayList;
008 import java.util.HashMap;
009 import java.util.List;
010 import java.util.Map;
011  
012 import org.apache.http.HttpResponse;
013 import org.apache.http.NameValuePair;
014 import org.apache.http.client.entity.UrlEncodedFormEntity;
015 import org.apache.http.client.methods.HttpPost;
016 import org.apache.http.impl.client.DefaultHttpClient;
017 import org.apache.http.message.BasicNameValuePair;
018  
019 public class NewsService {
020  
021     public static final int POST = 1;
022     public static final int GET = 2;
023     public static final int HttpClientPost = 3;
024  
025     /**
026      * 保存数据
027      *
028      * @param title
029      *            标题
030      * @param length
031      *            时长
032      * @param flag
033      *            true则使用POST请求 false使用GET请求
034      * @return 是否保存成功
035      * @throws Exception
036      */
037     public static boolean save(String path, String title, String timelength,
038             int flag) throws Exception {
039         Map<String, String> params = new HashMap<String, String>();
040         params.put("title", title);
041         params.put("timelength", timelength);
042         switch (flag) {
043         case POST:
044             return sendPOSTRequest(path, params, "UTF-8");
045         case GET:
046             return sendGETRequest(path, params, "UTF-8");
047         case HttpClientPost:
048             return sendHttpClientPOSTRequest(path, params, "UTF-8");
049         }
050         return false;
051     }
052  
053     /**
054      * 通过HttpClient框架发送POST请求
055      * HttpClient该框架已经集成在android开发包中
056      * 个人认为此框架封装了很多的工具类,性能比不上自己手写的下面两个方法
057      * 但是该方法可以提高程序员的开发速度,降低开发难度
058      * @param path
059      *            请求路径
060      * @param params
061      *            请求参数
062      * @param encoding
063      *            编码
064      * @return 请求是否成功
065      * @throws Exception
066      */
067     private static boolean sendHttpClientPOSTRequest(String path,
068             Map<String, String> params, String encoding) throws Exception {
069         List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放请求参数
070         if (params != null && !params.isEmpty()) {
071             for (Map.Entry<String, String> entry : params.entrySet()) {
072                 //BasicNameValuePair实现了NameValuePair接口
073                 pairs.add(new BasicNameValuePair(entry.getKey(), entry
074                         .getValue()));
075             }
076         }
077         UrlEncodedFormEntity entity = newUrlEncodedFormEntity(pairs, encoding);    //pairs:请求参数   encoding:编码方式
078         HttpPost httpPost = new HttpPost(path); //path:请求路径
079         httpPost.setEntity(entity);
080          
081         DefaultHttpClient client = new DefaultHttpClient(); //相当于浏览器
082         HttpResponse response = client.execute(httpPost);  //相当于执行POST请求
083         //取得状态行中的状态码
084         if (response.getStatusLine().getStatusCode() == 200) {
085             return true;
086         }
087         return false;
088     }
089  
090     /**
091      * 发送POST请求
092      *
093      * @param path
094      *            请求路径
095      * @param params
096      *            请求参数
097      * @param encoding
098      *            编码
099      * @return 请求是否成功
100      * @throws Exception
101      */
102     private static boolean sendPOSTRequest(String path,
103             Map<String, String> params, String encoding) throws Exception {
104         StringBuilder data = new StringBuilder();
105         if (params != null && !params.isEmpty()) {
106             for (Map.Entry<String, String> entry : params.entrySet()) {
107                 data.append(entry.getKey()).append("=");
108                 data.append(URLEncoder.encode(entry.getValue(), encoding));// 编码
109                 data.append('&');
110             }
111             data.deleteCharAt(data.length() - 1);
112         }
113         byte[] entity = data.toString().getBytes(); // 得到实体数据
114         HttpURLConnection connection = (HttpURLConnection) new URL(path)
115                 .openConnection();
116         connection.setConnectTimeout(5000);
117         connection.setRequestMethod("POST");
118         connection.setRequestProperty("Content-Type",
119                 "application/x-www-form-urlencoded");
120         connection.setRequestProperty("Content-Length",
121                 String.valueOf(entity.length));
122  
123         connection.setDoOutput(true);// 允许对外输出数据
124         OutputStream outputStream = connection.getOutputStream();
125         outputStream.write(entity);
126  
127         if (connection.getResponseCode() == 200) {
128             return true;
129         }
130         return false;
131     }
132  
133     /**
134      * 发送GET请求
135      *
136      * @param path
137      *            请求路径
138      * @param params
139      *            请求参数
140      * @param encoding
141      *            编码
142      * @return 请求是否成功
143      * @throws Exception
144      */
145     private static boolean sendGETRequest(String path,
146             Map<String, String> params, String encoding) throws Exception {
147         StringBuilder url = new StringBuilder(path);
148         url.append("?");
149         for (Map.Entry<String, String> entry : params.entrySet()) {
150             url.append(entry.getKey()).append("=");
151             url.append(URLEncoder.encode(entry.getValue(), encoding));// 编码
152             url.append('&');
153         }
154         url.deleteCharAt(url.length() - 1);
155         HttpURLConnection connection = (HttpURLConnection) new URL(
156                 url.toString()).openConnection();
157         connection.setConnectTimeout(5000);
158         connection.setRequestMethod("GET");
159         if (connection.getResponseCode() == 200) {
160             return true;
161         }
162         return false;
163     }
164 }


 在服务器上写一个ManageServlet用来处理POST和GET请求

 

01 package cn.roco.servlet;
02  
03 import java.io.IOException;
04 import javax.servlet.ServletException;
05 import javax.servlet.http.HttpServlet;
06 import javax.servlet.http.HttpServletRequest;
07 import javax.servlet.http.HttpServletResponse;
08  
09 public class ManageServlet extends HttpServlet {
10  
11     public void doGet(HttpServletRequest request, HttpServletResponse response)
12             throws ServletException, IOException {
13         request.setCharacterEncoding("UTF-8");
14         String title = request.getParameter("title");
15         String timelength = request.getParameter("timelength");
16         System.out.println("视频名称:" + title);
17         System.out.println("视频时长:" + timelength);
18     }
19  
20     public void doPost(HttpServletRequest request, HttpServletResponse response)
21             throws ServletException, IOException {
22         doGet(request, response);
23     }
24 }


为了处理编码问题 写了过滤器

01 package cn.roco.filter;
02  
03 import java.io.IOException;
04  
05 import javax.servlet.Filter;
06 import javax.servlet.FilterChain;
07 import javax.servlet.FilterConfig;
08 import javax.servlet.ServletException;
09 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.http.HttpServletRequest;
12  
13 public class EncodingFilter implements Filter {
14  
15     public void destroy() {
16         System.out.println("过滤完成");
17     }
18  
19     public void doFilter(ServletRequest req, ServletResponse resp,
20             FilterChain chain) throws IOException, ServletException {
21         HttpServletRequest request = (HttpServletRequest) req;
22         if ("GET".equals(request.getMethod())) {
23             EncodingHttpServletRequest wrapper=new EncodingHttpServletRequest(request);
24             chain.doFilter(wrapper, resp);
25         }else{
26             req.setCharacterEncoding("UTF-8");
27             chain.doFilter(req, resp);
28         }
29     }
30  
31     public void init(FilterConfig fConfig) throws ServletException {
32         System.out.println("开始过滤");
33     }
34  
35 }

01 package cn.roco.filter;
02  
03 import java.io.UnsupportedEncodingException;
04  
05 import javax.servlet.http.HttpServletRequest;
06 import javax.servlet.http.HttpServletRequestWrapper;
07 /**
08  * 包装 HttpServletRequest对象
09  */
10 public class EncodingHttpServletRequet extends HttpServletRequestWrapper {
11     private HttpServletRequest request;
12  
13     public EncodingHttpServletRequest(HttpServletRequest request) {
14         super(request);
15         this.request = request;
16     }
17  
18     @Override
19     public String getParameter(String name) {
20         String value = request.getParameter(name);
21         if (value != null && !("".equals(value))) {
22             try {
23                 value=new String(value.getBytes("ISO8859-1"),"UTF-8");
24             catch (UnsupportedEncodingException e) {
25                 e.printStackTrace();
26             }
27         }
28         return value;
29     }
30  
31 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值