Android Studio如何在片段中使用Request

时间:2018-03-26 16:08:42

标签: android android-studio android-fragments request httprequest

我想在一个片段中提出这个请求,但错误,我可以吗?谢谢!当我想在片段中实现它时,我有很多错误。Builder()OkHttpClient()所以我没有特别说错误

 String url = "https://freegeoip.net/json/"
    Request mRequest = new Request.Builder()
            .url(url)
            .build();
    Context mContext // A UI context
    new OkHttpClient().newCall(mRequest).enqueue(new Callback() {
        Handler mainHandler = new Handler(mContext.getApplicationContext().getMainLooper());

        @Override
        public void onResponse(Call call, Response response) {
            String responseBody = null;
            try {
                responseBody = response.body().string();
            } catch (final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // handle error
                    }
                });
            }

            final String finalResponseBody = responseBody;
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // handle response body
                    try {
                        JSONObject locationObject = new JSONObject(finalResponseBody);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void onFailure(Call call, final IOException e) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mNetworkListener.onNetworkError(e.getMessage());
                }
            });
        }
    });

0 个答案:

没有答案