Make an HTTP request with android

后端 未结 12 1091
时光取名叫无心
时光取名叫无心 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

    This is the new code for HTTP Get/POST request in android. HTTPClient is depricated and may not be available as it was in my case.

    Firstly add the two dependencies in build.gradle:

    compile 'org.apache.httpcomponents:httpcore:4.4.1'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    

    Then write this code in ASyncTask in doBackground method.

     URL url = new URL("http://localhost:8080/web/get?key=value");
     HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
     urlConnection.setRequestMethod("GET");
     int statusCode = urlConnection.getResponseCode();
     if (statusCode ==  200) {
          InputStream it = new BufferedInputStream(urlConnection.getInputStream());
          InputStreamReader read = new InputStreamReader(it);
          BufferedReader buff = new BufferedReader(read);
          StringBuilder dta = new StringBuilder();
          String chunks ;
          while((chunks = buff.readLine()) != null)
          {
             dta.append(chunks);
          }
     }
     else
     {
         //Handle else
     }
    

提交回复
热议问题