一個简单的okhttp访问网络的例子

private void phoneLogin() {
    OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .build();


    //使用Gson 添加 依赖 compile 'com.google.code.gson:gson:2.8.1'
    Gson gson = new Gson();
    //使用Gson将对象转换为json字符串
    String json = gson.toJson(loginRequest);

    //MediaType  设置Content-Type 标头中包含的媒体类型值
    RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
            , json);
    Request request = new Request.Builder()
            .url(tvIp.getText().toString() + APIUtils.LoginAPI.PHONE_LOGIN)//请求的url
            .post(requestBody)
            .build();

    //创建/Call
    Call call = okHttpClient.newCall(request);
    //加入队列 异步操作
    call.enqueue(new Callback() {
        //请求错误回调方法
        @Override
        public void onFailure(Call call, IOException e) {
            System.out.println("连接失败");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            });
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
           String result = response.body().string();
            Gson gson1 = new Gson();
            java.lang.reflect.Type type1 = new TypeToken() {}.getType();
            LoginResponse loginResponse = gson1.fromJson(((JsonObject)new JsonParser().parse(result)).get("content"), type1);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvToken.setText(loginResponse.getSuposToken());
                }
            });

        }
    });
}

你可能感兴趣的:(Android)