Android:使用 OkHttp 发送 HTTP Get请求,并解析所得的 JSON 数据。

布局 MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request"
        />
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    <TextView
        android:id="@+id/response_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    </ScrollView>
</LinearLayout>

MainActivity.java

package com.example.okhttpdemo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest =(Button)findViewById(R.id.send_request);
        responseText=(TextView)findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v){
        if(v.getId()==R.id.send_request){
            sendRequestWithOkHttp();
        }
    }
    
    private void sendRequestWithOkHttp(){
        new Thread(new Runnable(){
            @Override
            public void run(){
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://www.baidu.com")
                            .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                }catch(Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable(){
            @Override
            public void run(){
                responseText.setText(response);    
                 //responseText最初由TextView responseText;定义,代表TextView对象。
            }
        });
    }
}

安卓 9 加强了保密性,导致无法进行非加密的 http 网络请求

解决方法:

在 AndroidManifest.xml 的 application 标签中新加:

android:usesCleartextTraffic="true"

运行一下,如下图所示:

在这里插入图片描述
获取json数据

只需要把这行代码

Request request = new Request.Builder()
                            .url("http://www.baidu.com")
                            .build();

改成这样

Request request = new Request.Builder()
                            .url("http://10.0.2.2:8080/Demo22/get_data.json")
                            //测试 url 地址  http://10.0.2.2:8080/Demo22/get_data.json
                            .build();

运行一下,如下图所示:

在这里插入图片描述

使用 GSON 解析JSON数据

先添加依赖

implementation 'com.google.code.gson:gson:2.7'

再新建一个 App 类,写一个 javabean

package com.example.okhttpdemo;

public class App {
    private String id;
    private String name;
    private String version;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}

接着在下面重新写一个 parseJSONWithGSON 方法:

private void parseJSONWithGSON(final String jsonData){
        Gson gson =new Gson();
        List<App> appList = gson.fromJson(jsonData,new TypeToken<List<App>>()
        {}.getType());
        runOnUiThread(new Runnable(){
            @Override
            public void run(){
                //responseText.setText(response);
                for(App app:appList){
                    responseText.append("id is "+app.getId()+"\n");
                    responseText.append("name is "+app.getName()+"\n");
                    responseText.append("version is "+app.getVersion()+"\n");
                }
            }
        });
    }

运行一下,如下图所示:

在这里插入图片描述

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值