欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

程序员文章站 2024-01-19 17:07:58
...

一.使用Eclipse的web服务端(先写web服务端Android端才能调

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

login.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>
    <h1>登录页面</h1>
	<form action="login.do" method="get">
		用户名:<input type="text" name="uname"/><br/>
		密码:<input type="password" name="upass"/><br/>
		<input type="submit" value="登录"/><br/>
	</form>
</body>
</html>
LoginServlet.java

package com.zking.servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	    	      req.setCharacterEncoding("UTF-8");
	    	      resp.setContentType("text/html; charset=UTF-8");
	    	      
	    	      //获取用户名和密码
			      String uname=req.getParameter("uname");
			      String upass=req.getParameter("upass");
			      System.out.println(uname+" "+upass);//测试
			      
			      String result=null;//定义一个结果字符串
			      //判断
				  if("admin".equals(uname) && "123".equals(upass)){
					   result="成功success!";
				  }else{
					   result="失败fail!";
				  }
				  //在页面上打印
				  PrintWriter pw=resp.getWriter();
				  pw.write(result);
				  pw.close();
		}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ServerForAndroid</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <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>
  
</web-app>
二.Android端

技术1:登录(用Get方式提交)

Url路径

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

技术2:登录(用POST方式提交)

注:web端改为post提交方式

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

技术3:登录(用第三方AsyncHttpClient)

导jar包:android-async-http-1.4.4.jar

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

HttpClient导致不可以问题:

useLibrary 'org.apache.http.legacy'

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)



(案例)android端具体代码实现如下:

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)

activity_main.xml

<?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"
    >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"
        android:id="@+id/et_main_uname"
        />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:id="@+id/et_main_upass"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(GET)"
        android:onClick="loginGet"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(Post)"
        android:onClick="loginPost"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录(AsyncHttpClient)"
        android:onClick="loginAsyncHttpClient"
        />

</LinearLayout>

清单文件AndroidManifest.xml

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

MainActivity.java

package com.zking.android32_commitdata;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
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.TextHttpResponseHandler;

import org.apache.http.Header;

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

public class MainActivity extends AppCompatActivity {

        private EditText et_main_uname;
        private EditText et_main_upass;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            et_main_uname = (EditText) findViewById(R.id.et_main_uname);
            et_main_upass = (EditText) findViewById(R.id.et_main_upass);
        }

        public void loginGet(View view){
              String uname=et_main_uname.getText().toString();//一点击登录就拿用户名及密码
              String upass=et_main_upass.getText().toString();
              //拿Eclipse里面的业务逻辑路径9(cmd查ip地址,把localhost改为ip地址)
              String path="http://192.168.43.163:8080/ServerForAndroid/login.do";
              new MyGetTask().execute(uname,upass,path);//调方法
        }
        class MyGetTask extends AsyncTask {
                @Override
                protected Object doInBackground(Object[] params) {//专门拿数据
                        String uname=params[0].toString();
                        String upass=params[1].toString();
                        String path=params[2].toString();

                        try {
                              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 (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException 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 loginPost(View view){
                String uname=et_main_uname.getText().toString();
                String upass=et_main_upass.getText().toString();
                String path="http://192.168.43.163:8080/ServerForAndroid/login.do";
                new MyPostTask().execute(uname,upass,path);//调方法
        }
        class MyPostTask extends AsyncTask{
                @Override
                protected Object doInBackground(Object[] params) {
                        String uname=params[0].toString();
                        String upass=params[1].toString();
                        String path=params[2].toString();
                        try {
                             URL url=new URL(path);
                             HttpURLConnection conn= (HttpURLConnection) url.openConnection();
                             conn.setRequestMethod("POST");
                             conn.setConnectTimeout(5000);//超时时间

                             //admin 123长度21,因为(uname=admin&upass=123)
                             String s="uname="+uname+"&upass="+upass;
                             //添加请求头
                             conn.setRequestProperty("Content-Length",s.length()+"");
                             conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

                             conn.setDoOutput(true);//允许对外输出数据

                             OutputStream os=conn.getOutputStream();//写数据OutputStream
                             os.write(s.getBytes());//把数据传递给服务器了

                             if(conn.getResponseCode()==200){//拿到返回结果
                                    InputStream is=conn.getInputStream();
                                    BufferedReader br=new BufferedReader(new InputStreamReader(is));
                                    String str=br.readLine();
                                    return str;
                             }
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (ProtocolException e) {
                            e.printStackTrace();
                        } catch (IOException 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 loginAsyncHttpClient(View view){
                String uname=et_main_uname.getText().toString();
                String upass=et_main_upass.getText().toString();//值
                String path="http://192.168.43.163:8080/ServerForAndroid/login.do";
                //导jar包
                AsyncHttpClient ahc=new AsyncHttpClient();
                RequestParams params=new RequestParams();
                params.put("uname",uname);//把用户名密码给了它("键:必须和服务器保持一致",值:与上面一样)
                params.put("upass",upass);

                ahc.post(this,path,params,new TextHttpResponseHandler(){
                        //Ctrl+O重写方法
                        @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();
                        }
                });
        }




}

效果图:

32.Android端向web端(服务器)提交数据(GET-POST-AsyncHttpClient)