android okhttp 响应

本文依赖是okhttp:4.4.0
import android.os.Bundle;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

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

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

TextView txtString;
public String url= "https://www.baidu.com";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtString= (TextView)findViewById(R.id.txtString);

    try {
        run();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

void run() throws IOException {

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url(url)
            .build();

    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(@NotNull okhttp3.Call call, @NotNull IOException e) {
            call.cancel();
        }
        @Override
        public void onResponse(@NotNull okhttp3.Call call, @NotNull Response response) throws IOException {
            final String myResponse = response.body().string();
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    txtString.setText(myResponse);
                }

            });
        }
    });
}

}

上一篇:好用的自定义Okhttp日志拦截器


下一篇:okhttp像指定url发送图片并且获得返回值