Home java Working with HttpURLConnection in Android, polechenie information on GET

Working with HttpURLConnection in Android, polechenie information on GET

Author

Date

Category

It is necessary to get the result of GET query Android and the return value from the method.
Solved! Thank you all for your participation!

public void sayHello (View view) throws IOException {
    Thread httpThread = new Thread (new Runnable () {
      public void run () {
        String mybla = sendGet ();
      }
    });
    httpThread.start ();
  }
private String sendGet () {
    Try {
      String mystr = "http://www.pravda.com.ua";
      URL obj = new URL (mystr);
      HttpURLConnection con = (HttpURLConnection) obj.openConnection ();
      con.setRequestMethod ( "GET");
      con.setRequestProperty ( "User-Agent", "Mozilla / 5.0");
      con.setRequestProperty ( "Accept-Charset", "UTF-8");
      InputStream response = con.getInputStream ();
      Scanner s = new Scanner (response) .useDelimiter ( "\\ A");
      String result = s.hasNext ()? s.next (): "";
      RETURN RESULT;
    }
    catch (Exception e) {
      return e.toString ();
    }
  }

Answer 1, Authority 100%

All of doing the right thing. To read the stream and get out of it String , can use, for example, library Apache commons IOUtils ( off. site). With its help:

String result = IOUtils.toString (inputStream);

If predpochetaete the way without third-party libraries (which I welcome because it allows you to learn something new about the language in which you are a beginner), do like this:

Scanner s = new Scanner (inputStream) .useDelimiter ( "\\ A");
String result = s.hasNext ()? s.next (): "";

UPD :

Wrap in

new Thread (new Runnable () {
   public void run () {
    // call your code to a network request
   }
  .}) Start ();

When your query returned a result within your Thread , to change the interface element you need to do it from the UI-thread. To do this, use the Context.runOnUiThread ();

.


Answer 2

The code using liby OkHttp

OkHttpClient client = new OkHttpClient.Builder () build ().;
String url = ...;
Request.Builder request = new Request.Builder ();
request.url (url);
request.get ();
. Response response = client.newCall (request.build ()) execute ();
. String response = response.body () string ();
System.out.println (response);

It is necessary to remember that requests for android in the network can be done with API14 just outside the UI thread. For example through AsynkTask, Thread etc

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions