OKHttp 与 gson 用法

json工具

setting->plugin->gesonformat-

get 请求与 gson 用法


public class MainActivity extends AppCompatActivity {

    private final  String TAG = MainActivity.class.getCanonicalName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                getRequest();
            }
        }
        ).start();

    }
    private  void getRequest(){
        String url = "http://guolin.tech/api/china";
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
               // Log.d(TAG, "onResponse: " + response.body().string());
                String responseString = response.body().string();
//因为joson数据最外面是[]所以用JSONArray来接收json字符串
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(responseString);
                    //获取第一个jsonobject的数据
                    String province1 = jsonArray.getJSONObject(0).toString();
                    //将json数据与实体类相关联
                    Gson gson = new Gson();
                    Province province = gson.fromJson(province1,Province.class);
                    Log.e(TAG, "json对象: "+province.getProvinceName());
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });
    }
}

依赖


compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile 'com.squareup.okio:okio:1.9.0'
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

 

权限

<uses-permission android:name="android.permission.INTERNET"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值