Android 请求http接口,sdk27,解析json,Vincent

本文详细介绍了在Android应用中使用OkHttp进行HTTP请求的方法,包括POST与GET请求的实现,以及如何利用Gson库解析JSON响应为Java对象。同时,强调了避免在主线程中执行网络操作的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Post方式body带json的同步请求

导入依赖

 implementation 'com.squareup.okhttp3:okhttp:3.8.1'
// gson解析的依赖
    implementation 'com.google.code.gson:gson:2.8.0'

// Retrofit2的依赖
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
// gson解析的依赖
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

实现


try {

 String json="{\n" +
         "\t\t\t\"loginName\":\"st\",\n" +
         "\t\t\t\"password\":\"j1\"\n" +
         "\t\t\n" +
         "\t\t\t}";

 OkHttpClient client =new OkHttpClient();
 
 
 Request request=new Request.Builder()
         .url("http://www.yun.cn/wsjc/app/Login")
         .post(RequestBody.create(MediaType.parse("application/json"),json))
         .build();
    
 Response response=client.newCall(request).execute();
    String result =response.body().string();
    result.toCharArray();

}

Post方式带参数的同步请求接口

try {
    FormBody.Builder params=new  FormBody.Builder();
     params.add("username","lisi");
     params.add("password","123456");


 OkHttpClient client =new OkHttpClient();

 Request request=new Request.Builder()
         .url("http://172.81.240.47:8080/users/Login")
         .post(params.build())
         .build();

 Response response=client.newCall(request).execute();
    String result =response.body().string();
    result.toCharArray();
}

Get方式同步请求接口

try {
 OkHttpClient client =new OkHttpClient();


 Request request=new Request.Builder()
         .url("http://www.05n.cn/wsjc/Device/AppLogin.do?userID=jnst&userPassword=jn21")
         .build();

 Response response=client.newCall(request).execute();
    String result =response.body().string();
    result.toCharArray();

}

在Android请求http不能在主线程中

public  void send_OnClick(View v)
    {
        Log.i("xx", "click send");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {


                  //调用接口
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }).start();
    }

使用Gson解析json获取类对象

Step1导入依赖库

// gson解析的依赖
implementation ‘com.google.code.gson:gson:2.8.0’
// gson解析的依赖
implementation ‘com.squareup.retrofit2:converter-gson:2.3.0’

Step2

调试代码,根据请求成功获取的json串格式,通过在线,JSON生成Java实体类。在项目中新建java类,命名为xxxxBean.java 。
在这里插入图片描述
在这里插入图片描述

Step3使用Gson解析

Gson gson = new Gson();
LoginReceivedBean mLoginReceivedBean=gson.fromJson(result,LoginReceivedBean.class);
mLoginReceivedBean.toString();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值