Android 采用get方式提交数据到服务器

时间:2022-12-21 05:15:55

首先搭建模拟web 服务器,新建动态web项目,servlet代码如下:

package com.wuyudong.web;

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; import org.apache.catalina.User; /**
* Servlet implementation class LoginServlet
*/
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("用户名:" + username);
System.out.println("用户名:" + password);
if ("wuyudong".equals(username) && "123".equals(password)) {
response.getOutputStream().write("login success".getBytes());
} else {
response.getOutputStream().write("login failed".getBytes()); }
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
} }

再新建一个jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录页面</title>
</head>
<body>
<form action="LoginServlet" method="get"> 用户名:<input name="username" type="text"><br> 密码:<input
name="password" type="password"><br> <input
type="submit"> </form> </body>
</html>

新建android项目,页面布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入用户名"
android:inputType="text" /> <EditText
android:id="@+id/et_pwd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入密码"
android:inputType="textPassword" />
<Button
android:onClick="login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="登录"
/> </LinearLayout>

Android 采用get方式提交数据到服务器

代码如下:

package com.wuyudong.loginclient;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); et_name = (EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd); } public void login(View view) { String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim(); if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)) {
Toast.makeText(this, "用户名密码不能为空", 0).show();
} else {
// 模拟http请求,提交数据到服务器
String path = "http://169.254.168.71:8080/web/LoginServlet?username="
+ name + "&password=" + pwd;
try {
URL url = new URL(path);
// 2.建立一个http连接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 3.设置一些请求方式
conn.setRequestMethod("GET");// 注意GET单词字幕一定要大写
conn.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"); int code = conn.getResponseCode(); // 服务器的响应码 200 OK //404 页面找不到
// // 503服务器内部错误
if (code == 200) {
InputStream is = conn.getInputStream();
// 把is的内容转换为字符串
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while ((len = is.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
String result = new String(bos.toByteArray());
is.close();
Toast.makeText(this, result, 0).show(); } else {
Toast.makeText(this, "请求失败,失败原因: " + code, 0).show();
} } catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "请求失败,请检查logcat日志控制台", 0).show();
} } } }

添加权限:android.permission.INTERNET

运行项目后点击按钮后提示错误:

06-18 21:08:16.237: W/System.err(7417): android.os.NetworkOnMainThreadException

android强行让4.0以后的版本不去检查主线程访问网络。

解决办法,可以在onCreate里面加上下面这段代码:

StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

搞定