🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[Android网络编程之传递数据给服务器(二)](http://blog.csdn.net/fengyuzhengfan/article/details/39628543) 请尊重他人的劳动成果,转载请注明出处:[Android网络编程之传递数据给服务器(二)](http://blog.csdn.net/fengyuzhengfan/article/details/39628543) 我曾在《[Android网络编程之传递数据给服务器(一) ](http://blog.csdn.net/fengyuzhengfan/article/details/39621469)》 一文中介绍了如何通过GET方式传递数据给服务器,通过GET方式传递数据主要适用于数据大小不超过2KB,且对安全性要求不高的情况下。下面就介绍通过POST方式传递数据主到服务器。 ## 一、通过Post方式传递数据给服务器 通过Post方式传递数据给服务器是Android应用程序开发提交数据给服务器的一种主要的方式,适用于数据量大、数据类型复杂、数据安全性高的场合。 ### 1.创建服务器端: 服务器端项目结构: ![通过Post方式传递数据给服务器——服务器端项目结构](https://box.kancloud.cn/2016-02-19_56c6aa38e9975.jpg) ### 第一步:创建控制器Servlet ~~~ package com.jph.sp.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/ServletForPOSTMethod") public class ServletForPOSTMethod extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name= request.getParameter("name"); String pwd= request.getParameter("pwd"); System.out.println("name from POST method: " + name ); System.out.println("pwd from POST method: " + pwd ); } } ~~~ 至此服务器端项目已经完成。下面开始创建Android端项目。 ### 2.创建Android端: Android端项目结构: ![通过Post方式传递数据给服务器——Android端项目结构](https://box.kancloud.cn/2016-02-19_56c6aa3906256.jpg) ### 第一步:创建Android端项目的业务逻辑层 核心代码:SendDateToServer.java: ~~~ package com.jph.sp.service; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import android.os.Handler; /** * 通过POST方式向服务器发送数据 * @author jph * Date:2014.09.27 */ public class SendDateToServer { private static String url="http://10.219.61.117:8080/ServerForPOSTMethod/ServletForPOSTMethod"; public static final int SEND_SUCCESS=0x123; public static final int SEND_FAIL=0x124; private Handler handler; public SendDateToServer(Handler handler) { // TODO Auto-generated constructor stub this.handler=handler; } /** * 通过POST方式向服务器发送数据 * @param name 用户名 * @param pwd 密码 */ public void SendDataToServer(String name,String pwd) { // TODO Auto-generated method stub final Map<String, String>map=new HashMap<String, String>(); map.put("name", name); map.put("pwd", pwd); new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub try { if (sendPostRequest(map,url,"utf-8")) { handler.sendEmptyMessage(SEND_SUCCESS);//通知主线程数据发送成功 }else { //将数据发送给服务器失败 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } /** * 发送POST请求 * @param map 请求参数 * @param url 请求路径 * @return * @throws Exception */ private boolean sendPostRequest(Map<String, String> param, String url,String encoding) throws Exception { // TODO Auto-generated method stub //http://10.219.61.117:8080/ServerForPOSTMethod/ServletForPOSTMethod?name=aa&pwd=124 StringBuffer sb=new StringBuffer(url); if (!url.equals("")&!param.isEmpty()) { sb.append("?"); for (Map.Entry<String, String>entry:param.entrySet()) { sb.append(entry.getKey()+"="); sb.append(URLEncoder.encode(entry.getValue(), encoding)); sb.append("&"); } sb.deleteCharAt(sb.length()-1);//删除字符串最后 一个字符“&” } byte[]data=sb.toString().getBytes(); HttpURLConnection conn=(HttpURLConnection) new URL(url).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST");//设置请求方式为POST conn.setDoOutput(true);//允许对外传输数据 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");// 设置窗体数据编码为名称/值对 conn.setRequestProperty("Content-Length", data.length+""); OutputStream outputStream=conn.getOutputStream();//打开服务器的输入流 outputStream.write(data);//将数据写入到服务器的输出流 outputStream.flush(); if (conn.getResponseCode()==200) { return true; } return false; } } ~~~ ### 第三步:创建Activity ~~~ package com.jph.sp.activity; import com.jph.sp.service.SendDateToServer; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * 通过Post方式传递数据给服务器是Android应用程序开发 * 提交数据给服务器的一种主要的方式,适用于数据量大、 * 数据类型复杂、数据安全性高的场合。 * @author jph * Date:2014.09.27 */ public class MainActivity extends Activity { private EditText edtName,edtPwd; private Button btnSend; Handler handler=new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case SendDateToServer.SEND_SUCCESS: Toast.makeText(MainActivity.this, "登陆成功", Toast.LENGTH_SHORT).show(); break; case SendDateToServer.SEND_FAIL: Toast.makeText(MainActivity.this, "登陆失败", Toast.LENGTH_SHORT).show(); break; default: break; } }; }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edtName=(EditText)findViewById(R.id.edtName); edtPwd=(EditText)findViewById(R.id.edtPwd); btnSend=(Button)findViewById(R.id.btnSend); btnSend.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String name=edtName.getText().toString(); String pwd=edtPwd.getText().toString(); if (edtName.equals("")||edtPwd.equals("")) { Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_LONG).show(); }else { new SendDateToServer(handler).SendDataToServer(name, pwd); } } }); } } ~~~ 至此Android端项目已经完成了。下面就让我们看一下APP运行效果吧: Android运行效果图: ![通过Post方式传递数据给服务器——运行效果图](https://box.kancloud.cn/2016-02-19_56c6aa391736a.jpg) ![通过Post方式传递数据给服务器——运行效果图](https://box.kancloud.cn/2016-02-19_56c6aa39290d1.gif)