服务端网页Android Post请求详解
一、创建Web服务
1. 环境准备
开发工具:Eclipse和MyEclipse(用于编写Android客户端和服务端代码)。
服务器:Tomcat服务器,用于部署Servlet。
2. 创建Servlet
2.1 创建LoginAction类
package com.android.Login; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONSerializer; public class LoginAction extends HttpServlet { private static final long serialVersionUID = 1L; private LoginService service; @Override public void init() throws ServletException { super.init(); service = new LoginDao(); // 初始化登录服务 } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); PrintWriter writer = response.getWriter(); String username = request.getParameter("username"); String password = request.getParameter("password"); List<Object> params = new ArrayList<Object>(); params.add(username); params.add(password); boolean flag = service.isUserExitLogin(params); // 调用服务判断用户是否存在 if (flag) { ResultMessage message = new ResultMessage(1, "登陆成功"); // 封装结果信息 Map<String, Object> map = new HashMap<String, Object>(); map.put("result", message); String jsonString = JSONSerializer.toJSON(map).toString(); // 结果封装成JSON并传给客户端 writer.println(jsonString); } else { writer.println("登录失败"); } writer.flush(); writer.close(); } }
2.2 配置web.xml
<servlet> <servlet-name>LoginAction</servlet-name> <servlet-class>com.android.Login.LoginAction</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginAction</servlet-name> <url-pattern>/loginaction</url-pattern> </servlet-mapping>
二、Android客户端发送POST请求
1. 创建Activity布局文件activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/etUsername" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <EditText android:id="@+id/etPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/etUsername"/> <Button android:id="@+id/butPost" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/etPassword" android:text="提交"/> </RelativeLayout>
2. 编写MainActivity类
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.UrlEncodedFormEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; public class MainActivity extends Activity { private EditText mEtUsername; private EditText mEtPassword; private Button mButPost; private String LOGIN_URL = "http://10.0.2.2:8080/webtest/loginaction"; // 注意模拟器中的IP地址是10.0.2.2 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mEtUsername = findViewById(R.id.etUsername); mEtPassword = findViewById(R.id.etPassword); mButPost = findViewById(R.id.butPost); mButPost.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { submitPost(); } }); } private void submitPost() { String username = mEtUsername.getText().toString(); String password = mEtPassword.getText().toString(); HttpPost httpPost = new HttpPost(LOGIN_URL); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); try { httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(httpResponse.getEntity()); Toast.makeText(MainActivity.this, "登录结果:" + result, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "请求失败", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); Toast.makeText(MainActivity.this, "发生异常", Toast.LENGTH_SHORT).show(); } } }
三、相关问题与解答
1. 为什么使用HttpPost而不是HttpGet?
答:HttpPost将数据放在请求体中进行传输,适合传输大量数据或敏感数据,而HttpGet将参数放在URL后面,不适合传输敏感数据且有长度限制,HttpPost更适合表单提交等操作。
2. 如何在Android中使用Handler更新UI?
答:在子线程中通过Handler发送消息到主线程,然后在主线程的handleMessage方法中更新UI,创建一个继承自Handler的内部类,并在其中实现handleMessage方法来处理从子线程发送的消息。
以上内容就是解答有关“服务端网页androidpost”的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/777157.html