Android download string from webpage - java

I am making an app that will download a string from a website and display it.
I tried many examples online and I've literally been searching for days for this, but I can't find a single solution.
From what I have read, I know I have to get the content of the url from another thread, but no tutorial showed me how to do this.
I have a textview on the layout and that will be where the html content will have to show up.
Can anybody show me an example of how this is done?

What about something like this?
public class MyAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... requestUrl)
{
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(requestUrl[0]);
try
{
ResponseHandler<String> responseHandler = new BasicResponseHandler();
result = httpClient.execute(request, responseHandler);
}
catch (IOException e)
{
Log.e("requestStringFromWebServer", "Whoops!", e);
}
httpClient.getConnectionManager().shutdown();
return result;
}
#Override
protected void onPostExecute(String result)
{
if (result != null)
{
// Handle the result from your request here...
}
}
}
And kick it off with
String myUrlStr; // Initialize this to your url
new MyAsyncTask().execute(myUrlStr);

Related

Get result from php in android studio using simple runnable threads without any external libraries

So, I know this might seems like a repeated question, but bear with me for a moment. In Android Studio, instead of using any external libraries (i.e., no JSON, no Volley, no Retrofit, nothing external), I plan to use simple runnable threads. These will fetch data using PHP stored on the localhost through the IP address of the WiFi which my system is using.
I know how to send a PHP update (the actual update codes are in PHP script), it's done like this:
Runnable runnableToUpdateDb = new Runnable() {
#Override
public void run() {
Log.d("DEBUG","RUNNING RUNNABLE");
try {
URL url = new URL("http://192.168.43.242/myapi/php_name.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String response = bufferedReader.readLine();
Log.d("DEBUG", response);
httpURLConnection.disconnect();
}catch (Exception e){
Log.d("DEBUG",e.toString());
}
}
};
And then simply running the PHP using thread upon the press of the button by:
Thread threadToUpdateDb = new Thread(runnableToUpdateDb);
threadToUpdateDb.start();
Now, the problem is in setting up a TextView that shows the updated/new data from the database though a different PHP.
The id I've described for this TextView in the layout is:
android:id="#+id/getdata"
I need help for implementing it in MainActivity.
The output for PHP is in the form of:
<br>8<br>
Here's how you perform a HTTP GET to an URL using plain Android. In this case I choose an AsyncTask so it would run the request aside from the Main Thread:
private class TareaGetFromDB extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String response = null;
try {
// Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(URL);
// Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
// code 200 equals HTTP OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
response = IOUtils.toString(content, "utf-8");
} catch (Exception ex) {
// TODO handle exception
}
}
} catch(Exception ex) {
// TODO handle exception
}
return response;
}
#Override
protected void onPostExecute(String response) {
TextView myTextView = findViewById(R.id.getdata);
myTextView.setText(response);
}
}
This AsyncTask takes a String (the URL) as argument and returns a String (the response).
So you'll need to call it like this:
new TareaGetFromDB().execute("http://url.to/get/data");
You may need additional work before setting the text to the TextView to remove the surronding <br>, or you can remove them from the server response

Android - HTTP GET on separate thread

Background:
I am new to android programming. I want to simply do an http get request to a local server.
I want to pass this request a name as a parameter and want to get a return in json. This issue that I cannot execute it on the main thread. How can I do this?
Here is what I tried:
main class:
itemsAdapter.add(get.getName(device.getName()));
Seperate class in same file:
private class httpGet extends AsyncTask<Editable, Void, Integer> {
protected String doInBackground(Editable... params) {
Editable editable = params[0];
return getName(editable.toString());
}
final String getName(String btName) {
HttpResponse response = null;
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
URI website = new URI("http://192.168.1.105/getName.php?q=" + btName);
request.setURI(website);
response = client.execute(request);
// Convert String to json object
JSONObject json = new JSONObject(response.toString());
// get LL json object
JSONObject json_Name = json.getJSONObject("Name");
// get value from LL Json Object
name = json_Name.getString("value"); //<< get value here
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
// Do something to recover ... or kill the app.
}
return result;
}
protected void onPostExecute(Integer result) {
// here you have the result
}
I am not sure if this is even a good way to do this task. I also have no idea how I would call it.
AsyncTask allows you to perform a background operation in a different thread without manipulating threads/handlers.
It should be this way:
private class httpGet extends AsyncTask<ParamForDoInBackground, ParamForOnProgressUpdate, ParamForOnPostExecute> {
protected Long doInBackground(ParamForDoInBackground... urls) {
// do the request here
}
protected void onProgressUpdate(ParamForOnProgressUpdate progress) {
// if you need to show any progress of the
// request from doInBackground
}
protected void onPostExecute(ParamForOnPostExecute result) {
// this method will run when doInBackground
// is done executing
}
}
Then you can execute an AsyncTask:
new httpGet().execute(ParamForDoInBackground);
You can use the following as a reference: AndroidBackgroundProcessing and Android Developer AsyncTask
You should learn how the asyncTask work. Inside DoInBackground you should to put the code referent to the HTTPRequest. I recommend to use methods to improve the understanding of code. Here is an example of one of my apps:
public String query(String uri) {
HttpClient cliente = new DefaultHttpClient();
HttpContext contexto = new BasicHttpContext();
HttpPost httpPost = new HttpPost(uri);
HttpResponse response = null;
String resultado=null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("dato", cod_restaurante));
httpPost.setEntity(new UrlEncodedFormEntity(params));
response = cliente.execute(httpPost, contexto);
HttpEntity entity = response.getEntity();
resultado = EntityUtils.toString(entity, "UTF-8");
} catch (Exception e) {
// TODO: handle exception
}
return resultado;
}
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params)
{
result=query(params[0]);
return result;
}
protected void onPostExecute(final String resultadoDoInBackground)
{
//here put the code to modify the UI
}
}
Then in your activity onCreate() method you execute the Asynktask.
new MyAsyncTask().execute(" ");
You can read more about AsyncTask here:
AsyncTask Android Developer

Send data from android to website but no result returned

I am totally new in java and android.. I am sure I did it wrong on the code, please help me fix it
I try to send the content of a tweet as a String from an android application to this online parser: http://demo.ark.cs.cmu.edu/parse, and I want to retrieve the result of the parsing, here is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
String Tobetag = urlEncode(contentTweet);
new Analyser().execute();
}
private String urlEncode(String s){
try {
return URLEncoder.encode(s,"UTF-8").replace("+", "%20");
}
catch ( UnsupportedEncodingException e) {
throw new RuntimeException(s,e);
}
}
private class Analyser extends AsyncTask<Integer, Integer, Integer>
{
private String mUrl = "http://demo.ark.cs.cmu.edu/parse?sentence=";
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try
{
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(mUrl + mTobetag));
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader( new InputStreamReader(in) );
String result = reader.readLine();
System.out.println("Top");
System.out.println(result);
System.out.println("Bottom");
in.close();
}
catch(Exception e)
{
Log.e("Twitter", "doInBackground_" + e.toString());
}
return new Integer(1);
}
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected void onPostExecute(Integer i) {
}
}
I ran the code, no error reported but I didn't get the parse result, I only have this:
What can I do to get the result I wanted?
P.S. Also I am not sure I used the urlencoder right, it turn the slashes of the tweet content into %2F, but when I use the online parser by a browser, it shows that it doesn't change the slashed at all, please help
You are reading only the first line of the response, if you want to read the entire response you can do it like this:
String result = "";
for(String line;(line=br.readLine())!=null;){
result += line;
}
This will get you the entire http://demo.ark.cs.cmu.edu/parse page as a response, if you want the response to be only a JSON object, use this URL instead http://demo.ark.cs.cmu.edu/parse/api/v1/parse?sentence=....

How can I stop my app from crashing when trying to make a GET request with an ASyncTask?

I am really confused as to why I am having this problem. I am very new to android development so I am not really sure where to start when solving this problem. I have all the required permissions in the manifest file. <uses-permission android:name="android.permission.INTERNET" /> and <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />.
When a button is pressed myClickHandler is called and creates a URL with the two EditText's. After it does that it calls downloadWebPageTask which starts an ASyncTask. This AsyncTank takes the URL and then sends GET request. Here is my code.
public void myClickHandler(View view) {
SetText url = new SetText();
String stringUrl = url.createURL(artist_text.getText().toString(), release_text.getText().toString());
new DownloadWebpageTask().execute(stringUrl);
}
public class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
//SendStuff send = new SendStuff("mrblahblahblacksheep");
//return send.sendGet(urls[0]);
String url = urls[0];
String final_response = "FAILED!";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(request);
final_response = response.toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return final_response;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
result_text.setText(result);
}
}
Every time I press the button in the Emulator the app crashes. None of the crash data is saved in the logcat so I am unsure as to wear to find out the reasons for the crash.
This is possibly the problem:
response = client.execute(request);
final_response = response.toString();
If response is null, then response.toString() will throw NPE and your app will crash.
Make error handling graceful.
Try returning null result from catch blocks when you encounter exceptions. Also, for NPEs make if-else blocks and return null explicitly.
In onPostExecute(...) check if result is null, then display some default text or else display expected result.

Login to a website with HTTP Basic Authentication from Android app

I've already searched for many ways to do this, but i can't find any working way.
I want to login to this site:
http://www.besselgymnasium.de/fileadmin/Vertretung/Vertretungsplan_Schueler/subst_001.htm which uses HTTP Basic Authentication using my android app to read out the source code, but i don't know how i could let my app login automatically.
Could somebody tell me how this can be achieved?
The last thing i tried was:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
quellcode = (TextView) findViewById(com.example.MainActivity.R.id.TextView01);
geschichte = (TextView) findViewById(com.example.MainActivity.R.id.geschichte);
datum1 = (TextView) findViewById(com.example.MainActivity.R.id.datum1);
datum1.setText("25.03.2014");
readWebpage(quellcode);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String credentials = "username" + ":" + "password";
Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Authorization", "Basic "+credentials);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
//END OF READING
#Override
protected void onPostExecute(String result) {
quellcode.setText(result);
}
}
public void readWebpage(View view) {
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[]{"http://username:password#www.besselgymnasium.de/fileadmin/Vertretung/Vertretungsplan_Schueler/subst_001.htm"});
}
}
To access the web site you have to add the Authorization header.
First you have to concatenate and encode with base64 your credentials:
string credentials = username + ":" + password;
string credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");
then you add this header to your httpClient:
httpGet.setHeader("Authorization", "Basic "+credBase64);
Feel free to ask if you need more help.
Try using SharedPreferences. In this way, you will be able to store the login details for the first time you start the app. Next time onwards, you can read those values.
Follow this tutorial for SharedPreferences:
Tutorials Point

Categories

Resources