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

android客户端与javaweb服务器端数据通信-异步Get

程序员文章站 2024-03-22 23:35:28
...
android studio端
package com.example.z_t.mytest3;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FirstActivity extends AppCompatActivity {
    private EditText username;
    private EditText password;
    private String uname;
    private String pwd;
    private String result;
    private String re;
    private boolean res;


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

        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);

        Button button = (Button)findViewById(R.id.login);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uname = username.getText().toString();
                pwd = password.getText().toString();
                Log.i("First", uname);
                Log.i("First", pwd);

                getHttp(uname,pwd, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String responseData = response.body().string();
                        int ii =responseData.length();
                        Log.i("First", responseData);
                        Log.i("First", String.valueOf(ii));
                        if (responseData.equals("true")){
                            res=true;
                        }else {
                            res=false;
                        }
                        Log.i("First", String.valueOf(res));
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (res){
                                    Toast.makeText(FirstActivity.this, "请求成功", Toast.LENGTH_SHORT).show();
                                    Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
                                    startActivity(intent);
                                }else {
                                    Toast.makeText(FirstActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });//回到主线程进行UI操作
                    }
                });//耗时操作都在子线程完成,getHttp方法会在子线程还没执行完得情况下全部执行完,
                   //所以第一次按下登陆时候默认为false,第二次子线程完成才后把布尔值改成true



            }
        });
    }

    private void getHttp(String username,String password,okhttp3.Callback callback) {
        OkHttpClient client = new OkHttpClient();

        String url = "http://192.168.150.1:8080/test2/login?name="+username+"&pwd="+password;
        Log.i("First", url);
        Request request = new Request.Builder()
                .url(url)
                .method("GET",null)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);


    }

    private String parseXMLWithPull(String xmlData) {
        try{
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            while (eventType!=XmlPullParser.END_DOCUMENT){
                String nodeName = xmlPullParser.getName();
                switch (eventType){
                    case XmlPullParser.START_TAG:{
                        if ("td".equals(nodeName)){
                            result = xmlPullParser.nextText();
                        }
                        break;
                    }
                    case XmlPullParser.END_TAG:{
                        if ("tr".equals(nodeName)){
                            Log.i("First",result);
                        }
                    }
                    default:break;
                }
                eventType = xmlPullParser.next();
            }


                }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }


        private void postHttp(final String username,final String password){
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("username",username)
                        .add("password",password)
                        .build();
                Request request = new Request.Builder()
                        .url("http://192.168.150.1:8080/test2/login")
                        .post(body)
                        .addHeader("content-type","multipart/form-data")
                        .build();
                try {
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("First",parseXMLWithPull(responseData));

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
}

服务器端

package servlet;

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

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 net.sf.json.JSONObject;

/**
 * Servlet implementation class login
 */
@WebServlet("/login")
public class login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public login() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String name=request.getParameter("name").trim();         
        String pwd=request.getParameter("pwd").toString();  
        
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        
        System.out.println("name:"+name+"   pwd:"+pwd);  
        System.out.println(name.length());  
        if(("aa").equals(name)&&("22").equals(pwd)){
        	System.out.println("true");  
        	out.print("true");//有换行字符串长度就多2
        	
        }else{
        	System.out.println("false");
        }
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");

        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("name:"+username+"   pwd:"+password);  
        if("admin".equals(username)&&"admin".equals(password)){
        	out.println("<tr>");
        	out.println("<td>true</td>");
        	out.println("</tr>");
        }else{
        	out.println("false");
        }
        
	}
	
	
	public static String getRequestBody(HttpServletRequest req) throws IOException {
	    BufferedReader reader = req.getReader();
	    String input = null;
	    StringBuffer requestBody = new StringBuffer();
	    while((input = reader.readLine()) != null) {
	    requestBody.append(input);
	    }
	    return requestBody.toString();
	    }

}