Android发送GET和POST以及HttpClient发送POST请求给服务器响应
jopen
12年前
效果如下图所示:
布局main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/title" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/title" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:numeric="integer" android:text="@string/timelength" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/timelength" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/button" android:onClick="save" android:id="@+id/button"/> </LinearLayout>
string.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">资讯管理</string> <string name="title">标题</string> <string name="timelength">时长</string> <string name="button">保存</string> <string name="success">保存成功</string> <string name="fail">保存失败</string> <string name="error">服务器响应错误</string> </resources>
package cn.roco.manage; import cn.roco.manage.service.NewsService; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity { private EditText titleText; private EditText lengthText; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); titleText = (EditText) this.findViewById(R.id.title); lengthText = (EditText) this.findViewById(R.id.timelength); } public void save(View v) { String title = titleText.getText().toString(); String length = lengthText.getText().toString(); String path = "http://192.168.1.100:8080/Hello/ManageServlet"; boolean result; try { // result = NewsService.save(path, title, length, NewsService.GET); //发送GET请求 // result = NewsService.save(path, title, length, NewsService.POST); //发送POST请求 result = NewsService.save(path, title, length, NewsService.HttpClientPost); //通过HttpClient框架发送POST请求 if (result) { Toast.makeText(getApplicationContext(), R.string.success, 1) .show(); } else { Toast.makeText(getApplicationContext(), R.string.fail, 1) .show(); } } catch (Exception e) { Toast.makeText(getApplicationContext(), e.getMessage(), 1).show(); Toast.makeText(getApplicationContext(), R.string.error, 1).show(); } } }
package cn.roco.manage.service; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; 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 NewsService { public static final int POST = 1; public static final int GET = 2; public static final int HttpClientPost = 3; /** * 保存数据 * * @param title * 标题 * @param length * 时长 * @param flag * true则使用POST请求 false使用GET请求 * @return 是否保存成功 * @throws Exception */ public static boolean save(String path, String title, String timelength, int flag) throws Exception { Map<String, String> params = new HashMap<String, String>(); params.put("title", title); params.put("timelength", timelength); switch (flag) { case POST: return sendPOSTRequest(path, params, "UTF-8"); case GET: return sendGETRequest(path, params, "UTF-8"); case HttpClientPost: return sendHttpClientPOSTRequest(path, params, "UTF-8"); } return false; } /** * 通过HttpClient框架发送POST请求 * HttpClient该框架已经集成在android开发包中 * 个人认为此框架封装了很多的工具类,性能比不上自己手写的下面两个方法 * 但是该方法可以提高程序员的开发速度,降低开发难度 * @param path * 请求路径 * @param params * 请求参数 * @param encoding * 编码 * @return 请求是否成功 * @throws Exception */ private static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception { List<NameValuePair> pairs = new ArrayList<NameValuePair>();// 存放请求参数 if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { //BasicNameValuePair实现了NameValuePair接口 pairs.add(new BasicNameValuePair(entry.getKey(), entry .getValue())); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding); //pairs:请求参数 encoding:编码方式 HttpPost httpPost = new HttpPost(path); //path:请求路径 httpPost.setEntity(entity); DefaultHttpClient client = new DefaultHttpClient(); //相当于浏览器 HttpResponse response = client.execute(httpPost); //相当于执行POST请求 //取得状态行中的状态码 if (response.getStatusLine().getStatusCode() == 200) { return true; } return false; } /** * 发送POST请求 * * @param path * 请求路径 * @param params * 请求参数 * @param encoding * 编码 * @return 请求是否成功 * @throws Exception */ private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder data = new StringBuilder(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { data.append(entry.getKey()).append("="); data.append(URLEncoder.encode(entry.getValue(), encoding));// 编码 data.append('&'); } data.deleteCharAt(data.length() - 1); } byte[] entity = data.toString().getBytes(); // 得到实体数据 HttpURLConnection connection = (HttpURLConnection) new URL(path) .openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(entity.length)); connection.setDoOutput(true);// 允许对外输出数据 OutputStream outputStream = connection.getOutputStream(); outputStream.write(entity); if (connection.getResponseCode() == 200) { return true; } return false; } /** * 发送GET请求 * * @param path * 请求路径 * @param params * 请求参数 * @param encoding * 编码 * @return 请求是否成功 * @throws Exception */ private static boolean sendGETRequest(String path, Map<String, String> params, String encoding) throws Exception { StringBuilder url = new StringBuilder(path); url.append("?"); for (Map.Entry<String, String> entry : params.entrySet()) { url.append(entry.getKey()).append("="); url.append(URLEncoder.encode(entry.getValue(), encoding));// 编码 url.append('&'); } url.deleteCharAt(url.length() - 1); HttpURLConnection connection = (HttpURLConnection) new URL( url.toString()).openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == 200) { return true; } return false; } }
在服务器上写一个ManageServlet用来处理POST和GET请求
package cn.roco.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ManageServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String title = request.getParameter("title"); String timelength = request.getParameter("timelength"); System.out.println("视频名称:" + title); System.out.println("视频时长:" + timelength); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
为了处理编码问题 写了过滤器
package cn.roco.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class EncodingFilter implements Filter { public void destroy() { System.out.println("过滤完成"); } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; if ("GET".equals(request.getMethod())) { EncodingHttpServletRequest wrapper=new EncodingHttpServletRequest(request); chain.doFilter(wrapper, resp); }else{ req.setCharacterEncoding("UTF-8"); chain.doFilter(req, resp); } } public void init(FilterConfig fConfig) throws ServletException { System.out.println("开始过滤"); } }
package cn.roco.filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; /** * 包装 HttpServletRequest对象 */ public class EncodingHttpServletRequest extends HttpServletRequestWrapper { private HttpServletRequest request; public EncodingHttpServletRequest(HttpServletRequest request) { super(request); this.request = request; } @Override public String getParameter(String name) { String value = request.getParameter(name); if (value != null && !("".equals(value))) { try { value=new String(value.getBytes("ISO8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return value; } }