安卓菜鸟的进阶之路-OkHttp

1.作用http请求

2.用法:

(1).由于为第三方公司开发,需向build.gradle添加OkHttp库的依赖

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'}

在旧的版本中, implementation为compile

(2).

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button sendRequest = (Button)findViewById(R.id.send_request);
    responseText = (TextView)findViewById(R.id.response_text);
    sendRequest.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {
            if(v.getId() == R.id.send_request){
                sendRequestWithOKHttp();

            }
        }
    });
}

private void sendRequestWithOKHttp(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://192.168.135.2:10000/student.xml")
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                showResponse(responseData);

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

        }
    }).start();
}


猜你喜欢

转载自blog.csdn.net/qq_41484460/article/details/80069462