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

android客户端与javaweb服务器端数据通信-Post-Json格式数据

程序员文章站 2022-03-15 22:26:17
...

客户端

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 com.google.gson.Gson;

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.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FirstActivity extends AppCompatActivity {
    private EditText username;
    private EditText password;
    private String uname;
    private String pwd;
    private String result;
    private boolean res;
    public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");


    @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();
//                                }
//                            }
//                        });
//                    }
//                });



//                postHttp(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();
//                                }
//                            }
//                        });
//
//                    }
//                });

                postJsonHttp(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();
                                }
                            }
                        });
                    }
                });



            }
        });
    }

    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(String username,String password,okhttp3.Callback callback){
            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();
            Call call = client.newCall(request);
            call.enqueue(callback);
        }

        private void postJsonHttp(String username,String password,okhttp3.Callback callback){
            OkHttpClient client = new OkHttpClient();
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);

            Gson gson = new Gson();
            String json = gson.toJson(user);//使用Gson将对象转换为json字符串
            Log.i("First", json);

//            RequestBody body = RequestBody.create(JSON,json);
            RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),json);

            Request request = new Request.Builder()
                    .url("http://192.168.150.1:8080/test2/login")
                    .post(body)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callback);
        }


}

服务器端

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

/**
 * Servlet implementation class login
 */
@WebServlet("/login")
public class login extends HttpServlet {
	private String name=null;
	private String pwd=null;
	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
		 name=request.getParameter("name");         
         pwd=request.getParameter("pwd");  
        
        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(("admin").equals(name)&&("admin").equals(pwd)){
        	System.out.println("true");  
        	out.print("true");
        	
        }else{
        	System.out.print("false");
        	out.print("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");
//        
//         name = request.getParameter("username");
//         pwd = request.getParameter("password");
//        System.out.println("name:"+name+"   pwd:"+pwd);  
//        System.out.println(name.length());  
//        
//        PrintWriter out = response.getWriter();
//        
//        if(("admin").equals(name)&&("admin").equals(pwd)){
//        	System.out.println("true");  
//        	out.print("true");
//        	
//        }else{
//        	System.out.print("false");
//        	out.print("false");
//        }
        
        String jsonString = getRequestBody(request);
        System.out.println(jsonString);

        JSONObject jsonObj = JSONObject.fromObject(jsonString);

        System.out.println(jsonObj);
        pwd = jsonObj.getString("password").toString();
        name = jsonObj.getString("username");
       
        System.out.println("name:"+name+"   pwd:"+pwd);   
        System.out.println(jsonObj.getString("username")); 
        System.out.println(name.length());  
        
        
        PrintWriter out = response.getWriter();
        if(("admin").equals(name)&&("admin").equals(pwd)){
        	System.out.println("true");  
        	out.print("true");
        	
        }else{
        	System.out.print("false");
        	System.out.print("ff");
        	out.print("false");
        }
        
//        String jsonStr = "{\"password\":\"\",\"username\":\"张三\"}";
//        System.out.println(jsonStr);
//        JSONObject jsonObj2 = JSONObject.fromString(jsonStr);
//        String uu = jsonObj2.getString("username");
//        String pp = jsonObj2.optString("password");
//        System.out.println(uu);  
//        System.out.println(pp);  
	}
	
	


}