OkHttp的简单使用

//get 请求

private void get() {

OkHttpClient okHttpClient =newOkHttpClient();

String url ="http://www.baidu.com";

Request request =newRequest

.Builder()

.url(url)

.tag(this)

.build();

Call call = okHttpClient.newCall(request);

call.enqueue(newCallback() {

@Override

public voidonFailure(Call call, IOException e) {

}

@Override

public voidonResponse(Call call, Response response)throwsIOException {

finalString result = response.body().string();

Logger.e(MainActivity.this, result);

runOnUiThread(newRunnable() {

@Override

public voidrun() {

mTvShow.setText(result);

}

});

}

});

//        try {

//            //android.os.NetworkOnMainThreadException同步请求,导致程序崩溃

//            Response response = call.execute();

//            String string = response.body().string();

//            mTvShow.setText(string);

//        } catch (IOException mE) {

//            mE.printStackTrace();

//        }

}

你可能感兴趣的:(OkHttp的简单使用)