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);
}
});
}
});
}
}
标签:void,okhttp3,响应,IOException,NotNull,okhttp,import,android,public 来源: https://www.cnblogs.com/loveyout/p/14118480.html