Save Html soure code to String - android

first i'm german, so sorry for my bad english ;)
Im coding an app for my school which gives the students a notification if a lesson is cancelled. My school updates the substitute plan on the internet. It's a .htm file. (http://www.dbg-filderstadt.de/fileadmin/dateien/Dokumente/w00000.htm)
So the point is that i'm new in Android/Java coding and i don't know how to get the information/source code of the website saved in a String.
Could you give me an example code how to do that?

If you want to simply make an HTTP connection to download a HTML file, you could for example use http://developer.android.com/reference/java/net/HttpURLConnection.html. You would then have to read the input stream from it and convert it to a string, and then probably also parse the HTML by some means.
However, note that having an app reading a HTML resource off the internet isn't really the normal or preferable way to do it, ideally you would want your information to be available through some kind of API. By downloading and parsing HTML your app becomes dependent on the HTML resource not changing and breaking your parsing code etc. This is really fragile.

The one way is to follow the android documentation for sending GET requests and to use the Volley library with the following code:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String pageContent = "";
String url ="http://www.dbg-filderstadt.de/fileadmin/dateien/Dokumente/w00000.htm";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
pageContent = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//do something
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
In this case, when your request is successful (become response code 200 Ok from the server - no errors), the system runs a method called onResponse and you become a string (named response), which is exactly the content of the page you made request to. So you could save it to your variable and use it later (for example I called this variable pageContent).
I attach you a link to the android documentation, too : https://developer.android.com/training/volley/simple.html
Do not forget to add in your AndroidManifest.xml the permissions for requesting the net:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
and the following dependency for the Volley library to your build.gradle file : compile 'com.mcxiaoke.volley:library:1.0.+'

Related

Android Volley: How to flush and disable cache?

On my Android phone, I use Volley to do an HTTP POST request. The server sent an error response indicating a problem in the JSON data that I have passed. I have fixed the error but the server still display the same error. I have tried to pass an empty JSON file and I still get the same error response so the response clearly comes from some cached data.
I have tried to use those 2 things to clear and disable the cache but it doesn't help:
mRequestQueue = Volley.newRequestQueue(this);
mRequestQueue.getCache().clear(); // <==== Here
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, url, dataObject, ...);
jsonObjReq.setShouldCache(false); // <==== Here
mRequestQueue.add(jsonObjReq);
How can I disable the Cache used by Volley or Android?
If I use Curl to execute the same request it works.
Thanks
I have been able to fix the issue. I was using JsonObjectRequest and the server didn't understand the JSON file that I was sending.
I'm now using StringRequest() and it works.
Here is the non working code using JsonObjectRequest:
https://www.thethingsnetwork.org/forum/t/error-when-trying-to-add-an-end-device-from-http-api/55088/18?u=oliviergrenoble
And here is the working code using StringRequest:
https://www.thethingsnetwork.org/forum/t/error-when-trying-to-add-an-end-device-from-http-api/55088/21?u=oliviergrenoble
I have probably done something wrong in JsonObjectRequest version!

How to upload an image on a server using authorization and show the received json response in Android?

I am new to Android. I want to upload an image to a server and show the received json response after some parsing.
I am trying to use Android upload service (refer: (1) https://www.simplifiedcoding.net/android-upload-image-to-server/
(2) https://github.com/gotev/android-upload-service) but I don't know how to add authorization header in it. I tried to read the code in the github link, but couldn't understand.
The things I want to know are:
What is the best method to upload a file on a server using authorization.
Does Android provide something or is it better to use libraries? (I read that HttpURLConnection can help, but also read that it's better to use libraries for large files, but the source didn't look trustworthy, also I have lost from where I read that)
When I get through the uploading part, how do I approach the json part? (the uploading and response comes from a single url, I post the data in the request and it will give me some JSON response)
From where do I learn Android, so that I don't seek such spoon feeding answers.
The uploading code, in which I want to add authorization header:
public void uploadMultipart() {
String name = "app_image";
String path = getPath(filePath);
try {
String uploadId = UUID.randomUUID().toString();
new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
.addFileToUpload(path, "image")
.addParameter("name", name)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
I took it from the first reference, I have one doubt in it too: String uploadId = UUID.randomUUID().toString();.
What is its purpose and why am I using it? I feel like it's not necessary in my case, as I want to upload images using authorized usernames and not anonymous users.
Check this Documentation
I haven't myself used this library, but from what I can see here in the documentation you should be able add authorization with .addHeader(String headerName,String headerValue) This will add the Header to your request.
In your case you should do this if you have an access token:
new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
.addHeader("Authorization",<Put the authentication type here>+" "+<Put your access token here>)
.addFileToUpload(path, "image")
.addParameter("name", name)
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload();
If you are trying to authorize with username password, replace addHeader(String,String) with setBasicAuth(String username,String password)
Coming to your second question.
The purpose of using uuid here is probably used by the library to keep track of your uploads. from what I see in the documentation if you don't pass the upload id. The library generates it for you. It is used internally by the library.
Use Retrofit and Gson library easy to handle your APIs
Retofit - http://square.github.io/retrofit/
Retrofit tutorial - https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

How to get json data from post url

I have to get JSON from post url.
This is my url
URl: link
Result After process:
{
"success": false,
"error_code": null,
"data": {
"transaction_status": 0
}
}
When I hit this url, mutiple url are calling internally after a long process JSON response will display in WebView. I need to fetch this JSON response by hit this url without showing WebView
Please anybody help me out from this problem.
thanks
Add volley to your project just add the following line.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
for get json response
private void sendRequest(){
StringRequest stringRequest = new StringRequest(JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String json){
// here you can get json.
}
Please follow this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
You need to hit webservice using HttpUrlConnection class of android API and you can get the response in json string format.
http://www.itsalif.info/content/android-volley-tutorial-http-get-post-put
try this this will help
any more query you can ask
This url provided by OP (I mean #dev_mg99) does not consist of a "Server-side" redirect.
The JSON data on the webpage appears after "Javascript" execution.
And as much as I know doing HTTP POST/GET (using any method provided in android) will be useless in this scenario as the server is returning "webpage" and "not JSON data".
(Please correct me if I am wrong. So that I get to learn something new)
The only possible solution coming to my mind is:
1) Load the above url in a WebView
2) Keep on checking whether the WebView has loaded "completely"
3) If it has loaded completely Extract the "html" text of the WebView and obtain the desired JSON text.
No idea how to code (2)... So cannot provide any code.
How I came to know that?
Step 1:
Open above url in (say) google chrome. Wait for sometime and you will see that the page redirects to a webpage with following text:
{"success":false,"error_code":null,"data":{"transaction_status":0}}
which looks like a JSON string.
Step 2: Disable the JavaScript of the browser (For google chrome: Settings -> Show Advanced Settings -> Privacy... Content Settings --> Javascript... Click on "Do not allow any site to run JavaScript"
Step 3: Now, again, try to open above url in the browser... The page will not redirect anywhere.
According to which I conclude that the above url is redirected by JavaScript (Not from Server-Side)

Sending a post in android with bad encoding

I'm sending post content to a server from android.
The problem is that the data at the server arrives wrong, with encoding problems, for example "{" arrives as "%7B%".
This is the code from android:
RequestParams params = new RequestParams();
params.put("alta", "{s}");
String ruta = "http://www.something.com/receive";
client.post(ruta, params,
new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
}
}
The server part is just receiving this data, like:
$data = $this->request->data;
$data =file_get_contents('php://input');
This issue is not directly related to text encoding per se.
As can be seen from the docs for RequestParams, text values are directly included in the url. As all text that is included in URLs has to be encoded to only include characters that are allowed in URLs (ASCII), text is url encoded.
AsyncHttpClient automatically does that encoding in the background, so you receive the strings in encoded form on the php side.
In order to get the original text you sent, you can use the rawurldecode() or urldecode() function on the php side to decode the encoded string you receive.
You need to use URLEncoder.encode(...) the the data part of you request.
At the server URL decode it.
You should be fine.

How to efficiently manage image resources, both local and networked, in Android?

I am working on an app, which requires-
Pull contact details and images from the local contact book.
Some interval apart sync this contact data (all of it) to a server.
Pull contact data (images as well) from the server whenever needed.
I basically know how to implement them individually. For example, I have already managed to pull local contacts, I am yet to achieve 2 and 3. I have few questions regarding them.
Where do I save the images (both local and networked)? Do I need to save them in any particular folder? If yes then what is the recommended way of doing that?
I have used volley library in another project, and I am hoping to use it again here. AFAIK, volley caches networked images in the memory. But I believe that in my app, there can be users who will have more than 2000 contact data. My intuition is that not all the images will remain in the cache for ever, so if I want my app to work offline, I will need to images to be stored locally. I am confused about where to store the images and how to achieve that. Point to note, this app will be accessed frequently.
What is the recommended way of sending image data over the network to a server.
The questions may seem broad, but I feel that they are tightly coupled, considering a single app. I am expecting expert opinion on the recommended ways of achieving these features.
Thanks!
You typically save them either to your internal folder or to the SD card in your directory. The internal data folder will be locked to your app (unless the phone is rooted) and inacessible by other apps, the sd card will be only on 4.3 and higher. Either way you should manage the amount of data cached, set a limit and not allow it to go higher than that (kicking them out in some matter, most likely LRU or LFU). YOu'll need to do that by hand or find a library to do it for you, its not built into Android.
As for downloading them from the server- typically its just an HTTP request, with a webservice that will do any necessary privacy checking before sending down either an image result or an error. You don't want to do anything like JSON or the like here, it will just waste bandwidth.
There is no "recommended directory for images". The decision is up to you. But you must always remember that memory on user's device is finite and on some handsets even extra few megabytes are inappropriate expenditure. The docs are pretty clear.
Saving ~2000 photos on user's device is not a good idea. But again it's up to you. The Volley library is for general https interaction but not for images downloading, encoding and caching. Picasso is aimed to work with images: loads images from network or by Uri, has cache size settings and many other features.
It depends on your server. The most common way is just POST http request or multipart request if you need to send some additional data.
About third question, if you're going to keep using Volley, you can try to override the getBody() to return the image's bytes, rest of other parameters should be encoding within the URL, this way would use both of GET and POST method.
public class ContactRequest extends StringRequest {
public static String buildRequestUrl(String url,
Map<String, String> params, String paramsEncoding) {
StringBuilder urlBud = new StringBuilder(url).append('?');
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
urlBud.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
urlBud.append('=');
urlBud.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
urlBud.append('&');
}
return urlBud.toString();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding);
}
}
private String imageFilePath;
public ContactRequest(String url, String imageFilePath,
Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, listener, errorListener);
this.imageFilePath = imageFilePath;
}
#Override
public byte[] getBody() throws AuthFailureError {
return getBytesFromFile(new File(imageFilePath));
}
}
build the ContactRequest and serve to RequestQueue like this :
String originUrl = "http://.../contact_push.do";
String imageFilePath = "/sdcard/.../contact_avatar_path";
Map<String, String> params = new HashMap<String, String>();
params.put("firstName", "Vince");
params.put("lastName", "Styling");
new ContactRequest(
ContactRequest.buildRequestUrl(originUrl, params, HTTP.UTF_8),
imageFilePath, null, null);
'cause I never faced this problem before, so I don't sure this Request can reach to the server correctly, it's an un-test solution for me, hope can help.

Categories

Resources