Android - HTTP GET Request

后端 未结 4 2117
迷失自我
迷失自我 2020-12-29 12:30

I have developed a HTTP GET Method that clearly works.

public class GetMethodEx {


public String getInternetData() throws Exception{

        new TrustAllMa         


        
4条回答
  •  执念已碎
    2020-12-29 13:05

    HttpClient is deprecated. So new way to do: First, 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
     }
    

    Note: Don't forget to handle the Exceptions in code .

提交回复
热议问题