Android_Android与Web端的数据交互

WEB登录逻辑处理:

package com.zking.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 LoginServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
    //    super.service(arg0, arg1);
        String uname=req.getParameter("uname");
        String upass=req.getParameter("upass");
        String result="";
        if ("admin".equals(uname) && "123".equals(upass)) {
            result="success";
        }else{
            result="fail";
        }
        resp.getWriter().write(result);
    }

}

Web.xml配置Servler:

<servlet>
      <servlet-name>loginServlet</servlet-name>
      <servlet-class>com.zking.Servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>loginServlet</servlet-name>
      <url-pattern>/login.do</url-pattern>
  </servlet-mapping>


Android登录布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.android_webandandroid.MainActivity">
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入帐号"
        android:id="@+id/et_mian_uname"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:id="@+id/et_mian_upass"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过get方式提交"
        android:onClick="loginGet"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过post方式提交"
        android:onClick="loginPost"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="通过AsyncHttpClient方式提交"
        android:onClick="loginAsyncHttpClient"/>

</LinearLayout>

Activity代码:

package com.example.android_webandandroid;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.ResponseHandlerInterface;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private EditText et_mian_uname;
    private EditText et_mian_upass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_mian_uname = (EditText) findViewById(R.id.et_mian_uname);
        et_mian_upass = (EditText) findViewById(R.id.et_mian_upass);
    }
//通过谷歌的第三方
//需要导入jar包:android-async-http-1.4.4.jar
//以及类库:
useLibrary 'org.apache.http.legacy'


public void loginAsyncHttpClient(View view){ String uname=et_mian_uname.getText().toString(); String upass=et_mian_upass.getText().toString(); String path="http://193.168.3.53:8080/G160628_ServletForAndroid/login.do"; AsyncHttpClient ahc=new AsyncHttpClient(); RequestParams rp=new RequestParams(); rp.put("uname",uname); rp.put("upass",upass); ahc.post(MainActivity.this, path, rp, new TextHttpResponseHandler() { @Override public void onFailure(int statusCode, Header[] headers, String responseBody, Throwable error) { super.onFailure(statusCode, headers, responseBody, error); } @Override public void onSuccess(int statusCode, Header[] headers, String responseBody) { super.onSuccess(statusCode, headers, responseBody); Toast.makeText(MainActivity.this, responseBody, Toast.LENGTH_SHORT).show(); } }); } public void loginPost(View view){ String uname=et_mian_uname.getText().toString(); String upass=et_mian_upass.getText().toString();

//path为网络中逻辑层的路径,需要在局域网中,可以在控制面板中输入ipconfig获取IPv4 地址
  String path="http://193.168.3.53:8080/G160628_ServletForAndroid/login.do";

  new MyPostTask().execute(uname,upass,path); } class MyPostTask extends AsyncTask{ @Override protected Object doInBackground(Object[] objects) { String uname=objects[0].toString(); String upass=objects[1].toString(); String path=objects[2].toString(); try { URL url=new URL(path); HttpURLConnection coon= (HttpURLConnection) url.openConnection(); coon.setRequestMethod("POST"); coon.setConnectTimeout(5000); //uname与upass的名称必须与web端保持一致
String s="uname="+uname+"&upass="+upass; //添加请求头 coon.setRequestProperty("Content-Length",s.length()+""); coon.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); coon.setDoOutput(true);//允许对外输出数据 OutputStream os=coon.getOutputStream(); os.write(s.getBytes()); if (coon.getResponseCode()==200){ InputStream is=coon.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String str=br.readLine(); return str; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); String s= (String) o; Toast.makeText(MainActivity.this,s, Toast.LENGTH_SHORT).show(); } } public void loginGet(View view){ String uname=et_mian_uname.getText().toString(); String upass=et_mian_upass.getText().toString(); String path="http://193.168.3.53:8080/G160628_ServletForAndroid/login.do"; new MyGetTask().execute(uname,upass,path); } class MyGetTask extends AsyncTask{ @Override protected Object doInBackground(Object[] objects) { String uname=objects[0].toString(); String upass=objects[1].toString(); String path=objects[2].toString(); try {
//uname与upass的名称必须与web端保持一致
 URL url=new URL(path+"?uname="+uname+"&upass="+upass); HttpURLConnection connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); if (connection.getResponseCode()==200){ InputStream is=connection.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String s=br.readLine(); return s; } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); String s= (String) o; Toast.makeText(MainActivity.this,s, Toast.LENGTH_SHORT).show(); } }}

Android网络权限:

<uses-permission android:name="android.permission.INTERNET"></uses-permission>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值