Working with HttpURLConnection in Android, getting information by GET
You need to get the result of the GET
query in Android
and return the value from the method.
It's decided! Thank you all for participating!
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();
}
}
2 answers
You do everything right. To read a stream and get String
from it, you can use, for example, the library Apache commons IOUtils
(off. site). Using it:
String result = IOUtils.toString(inputStream);
If you prefer a method without third-party libraries (which I welcome, because it allows you to learn something new about the language in which you are new), then do something 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() {
//вызовите ваш код для сетевого запроса
}
}).start();
When your the request returned the result inside your Thread
, to change the interface element you will need to do it from the UI thread. To do this, use Context.runOnUiThread();
.
Code using the lib 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 );
We must remember that on Android, requests to the network can be made with API14 only outside the UI stream. For example, via AsynkTask, Thread etc