Make an HTTP request with android

后端 未结 12 1307
时光取名叫无心
时光取名叫无心 2020-11-21 06:38

I have searched everywhere but I couldn\'t find my answer, is there a way to make a simple HTTP request? I want to request a PHP page / script on one of my websites but I do

12条回答
  •  不要未来只要你来
    2020-11-21 07:24

    As none of the answers described a way to perform requests with OkHttp, which is very popular http client nowadays for Android and Java in general, I am going to provide a simple example:

    //get an instance of the client
    OkHttpClient client = new OkHttpClient();
    
    //add parameters
    HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
    urlBuilder.addQueryParameter("query", "stack-overflow");
    
    
    String url = urlBuilder.build().toString();
    
    //build the request
    Request request = new Request.Builder().url(url).build();
    
    //execute
    Response response = client.newCall(request).execute();
    

    The clear advantage of this library is that it abstracts us from some low level details, providing more friendly and secure ways to interact with them. The syntax is also simplified and permits to write nice code.

提交回复
热议问题