Android使用okhttp框架实现带参数Get和Post请求(附服务端完整代码)

由于工作需求,我从一个Java服务端开发人员转到了Android客户端,这篇博客的服务器端只是简单的写了个servlet,没有用框架。服务端没有连接数据库,实现了一个伪登陆。

服务端代码结构

Android使用okhttp框架实现带参数Get和Post请求(附服务端完整代码)_第1张图片

web.xml




  Archetype Created Web Application
  
  
    LoginServlet
    com.it.Servlet.LoginServlet
  
  
    LoginServlet
    /login.action
  

LoginServlet
package com.it.Servlet;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doGet(req, resp);
        resp.setContentType("text/html;charset=utf-8");
        resp.setHeader("content-type", "text/html;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username);
        System.out.println(password);
        if (username.equals("ycy")&password.equals("123")){
            resp.getWriter().print("登陆成功");
        }else {
            resp.getWriter().print("登陆失败");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //super.doPost(req, resp);
        doGet(req,resp);
    }

}

Android客户端,getTask.java这个是我用原生http写的,没有用上!!

Android使用okhttp框架实现带参数Get和Post请求(附服务端完整代码)_第2张图片

在build.gradle 里面添加jar包

 implementation 'com.squareup.okhttp3:okhttp:3.1.0'

在AndroidManifest.xml里面添加权限

 

activity_main.xml




    

    

    

    

MainActivity.java

package com.it;

import android.content.DialogInterface;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.IOException;

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


public class MainActivity extends AppCompatActivity {
    private EditText username;
    private EditText pwd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username =  findViewById(R.id.username);
        pwd =  findViewById(R.id.password);
    }
    //Get请求
    public void LoginGet(View view){
        String name=username.getText().toString();
        String password=pwd.getText().toString();
        String path="http://192.168.43.227:8080/demo_android/login.action?username="+name+"&password="+password;
        System.out.println(path);
        System.out.println("用户名:"+name);
        System.out.println("密码:"+password);

        OkHttpClient client =new OkHttpClient();
        Request request=new Request.Builder().url(path).get().build();
        client.newCall(request).enqueue(new Callback() {
            //失败
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("MainActivity","连接失败"+e.getLocalizedMessage());
            }
            //成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
              String  result = response.body().string();
                Log.d("MainActivity",result);
                if (response.body()!=null){
                    response.body().close();
                }
            }
        });

    }
    //Post请求
    public void LoginPost(View view){
        String name=username.getText().toString();
        String password=pwd.getText().toString();
        String url="http://192.168.43.227:8080/demo_android/login.action";

        OkHttpClient client=new OkHttpClient();
        //构建表单参数
        FormBody.Builder requestBuild=new FormBody.Builder();
        //添加请求体
        RequestBody requestBody=requestBuild
                    .add("username",name)
                    .add("password",password)
                    .build();

        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        System.out.println(request.toString());
        //异步请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("MainActivityPost","连接失败"+e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String  result = response.body().string();
                Log.d("MainActivity",result);
                if (response.body()!=null){
                    response.body().close();
                }
            }

        });
    }
}

最终效果

客户端后台:

Android使用okhttp框架实现带参数Get和Post请求(附服务端完整代码)_第3张图片

Android使用okhttp框架实现带参数Get和Post请求(附服务端完整代码)_第4张图片

 

你可能感兴趣的:(Android)