標籤:
首先搭建類比網頁伺服器,建立動態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>
代碼如下:
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);
搞定
Android 採用get方式提交資料到伺服器