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);
                }

            });
        }
    });
}

}

android okhttp 响应

上一篇:手机号、身份证号、邮箱验证


下一篇:移动端px转换rem 例如10px=0.1rem