é=é: need to show as it is - android

I am getting some response from server in text format, it's working fine but in some cases i didn't get string as it is.
Explanation:- My db have one name like cupcaké but when i parse data it's show me cupcaké. I want to show as it is like cupcaké.
I tried URL.Encode and URL.Decode function with the help of utf-8 but none of them helpful. I need universal solution which work for all special character not only for this character.
Here is my jsonparser class, can i need to make changes in this file? or somewhere?
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
URL url = new URL(str);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
json = jsonResults.toString();
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error processing Places API URL", e);
How can i show as it is on my screen?
Please give me any reference or hint.

After a long search, I found a good answer. These are html entities and can be shown by using the following code:
Html.fromHtml(Html.fromHtml((String) yourstring).toString());
Now every html entity's converted into the actual string. You can find more details here.

You need to work on Sms Encoding Concept .
Try some refrence:
http://www.codeproject.com/Tips/470755/Encoding-Decoding-7-bit-User-Data-for-SMS-PDU-PDU

Note that when you typed cupcaké in your question (before I edited it), the browser displayed it as cupcaké (here it is again, check the answer source: cupcaké). These are "html entities", and you can ask your favorite programming language to decode them into the corresponding character. In php, you'd use html_entity_decode().

Related

How to prevent denial of services(DOS) attacks in android?

I have used map in my android application. I passed origin and destination latlon and get data from map url then parse the response.
But while auditing below code as marked for DOS attack stating that "This code might allow an attacker to crash the program or otherwise make it unavailable to legitimate users."
Concern : What if attacker push too large file then it will go on line by line and loop will be run for too long.
Proposed solution : Do not allow to read more than specific file size, so that it won't read file beyond some limit
Here is my code :
String url = "https://maps.googleapis.com/maps/api/directions/json"+ "?" + str_origin + "&" + str_dest + "&" + "sensor=false";
private String downloadDataFromUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpsURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream),1024);
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
Please provide solution. Thanks in advance.
Edit 1:by calling append() it appends Untrusted data to a StringBuilder instance initialized with the default backing-array size (16). This can cause the JVM to over-consume heap memory space.
If you download from an unknown URL, the data can indeed be arbitrary and BufferedReader.readLine() can encounter a line so long the program cannot handle it. This question indicates that limiting BufferedReader line length may not be trivial.
Number of lines can be too big as well, in which case line count check instead of simple null check in the while loop seems to be enough.
Question is why would you allow the user to input an arbitrary URL and download it without checking. The URL can easily be a several GB binary file. Your first line indicates that you intend to use the Google Maps API, which AFAIK does not return excessively large lines, rendering the DOS concern moot (except in some ultrasecure applications, which I do not think Android is suitable to use for).

Is it possible to post at the same time a string and an image to a webserver?

There is a string variable and an image photo taken from the camera intent. The directory location of the photo is known. I want to make a HTTP post of the string variable and the image photo to a webserver at the same time. Is that possible ? If so , how to do it ?
From what I understand, you need to send an image and a string to your webserver within a single POST request. Here's how you'd proceed.
You first need to Base64 encode your image.
Start by converting your image into a byte array:
InputStream image = new FileInputStream(<path_to_image>);
byte[] buff = new byte[8192];
int readBytes;
ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
try {
while ( (readBytes = inputStream.read(buff) ) != -1) {
byteArrOS.write(buff, 0, readBytes);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] b = byteArrOS.toByteArray();
Then convert it to Base64:
String bsfEncodedImage = Base64.encodeToString(b, Base64.DEFAULT);
Then build a query with the the string and the resulting Base64 both encoded with URLEncoder and "utf-8":
strImgQuery = "str="+URLEncoder.encode(<string_data>, "utf-8")+"&image="+URLEncoder.encode(bsfEncodedImage, "utf-8");
Declare a new URL:
URL postUrl = new URL("http://<IP>/postreq");
Open the connection:
HttpURLConnection conn = (HttpURLConnection)postUrl.openConnection();
Set output to "true" (needed for a POST request but not for GET):
conn.setDoOutput(true);
Set the request method to POST:
conn.setRequestMethod("POST");
The timeout:
conn.setReadTimeout(1e4);
Buffer the output to the output stream and flush/run:
Writer buffWriter = new OutputStreamWriter(conn.getOutputStream());
buffWrite.write(strImgQuery);
buffWriter.flush();
buffWriter.close();
At server side you'll get the str and image POST params which is dependent on your server implementation.
Note that your url must follow the URL Specification, otherwise you'll get a MalformedURLException. If that's the case, be sure to check what exactly the issue is. For example if you use a non-existing ttp "protocol" instead of http your exception will look something like this:
java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:592)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.sendGetRequest(MalformedURLExceptionExample.java:28)
at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.main(MalformedURLExceptionExample.java:17)
Also, this is a synchronous operation and is ran on the UI thread. It might be costly or it might not depending on other operations you're already running and the size of the POST data. If the problem arises, run the job on another thread.
You can use URLEncoder
String strUrl = "http://192.168.1.9/impots/" +URLEncoder.encode("outil.php?action=OutilImporterDonneesMobile", "utf-8");
URL url = new URL(strUrl);

Howto do a simple ftp get file on Android

I can't find an example of a simple FTP access of a file anywhere, and the FTPClient class (which a couple of examples use) doesn't appear in the Android Class Index. I've got http access working, but how do I do a simple FTP get? All I want to do is download (for example):
ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/KABQ.TXT
It shouldn't require login, change directory, etc.
Just giving that URL to the http access methods don't seem to work.
This is similar to the question at:
unable to read file from ftp in android?
I tried a simple:
StringBuilder response = new StringBuilder();
URLConnection ftpConn;
try {
URL netUrl = new URL("ftp://tgftp.nws.noaa.gov/data/observations/metar/stations/KABQ.TXT");
ftpConn = netUrl.openConnection();
BufferedInputStream bufRd = new BufferedInputStream(ftpConn.getInputStream());
int temp;
while ((temp = bufRd.read()) != -1) {
response.append(temp);
}
bufRd.close();
} catch (Exception e) {
return "Failure";
}
but it gets an exception on getInputStream:
Unable to connect to server: Unable to configure data port
Also, there must be a more intelligent way to pull the data out of the stream buffer than byte-by-byte, isn't there? I can't find that either.
Lastly, I need to do both http and ftp access, is there any reason not to use URLConnection for both access types? or is it better to use HttpConnection for http and URLConnection for ftp?
Thanks!
Whew! I finally got it going. I gave up on the simple way that works in webOS and WPF/C# where you can just do a ftp:://... you have to use the FTPClient package.
After fixing the library access (Project | Properties | Java Build Path | Libraries | Add JARs...) I fiddled with the calls until it started working. Here's the sequence of my FTPClient calls. It wouldn't work until I set it in passive mode.
mFTPClient = new FTPClient();
mFTPClient.connect("tgftp.nws.noaa.gov");
mFTPClient.login("anonymous","nobody");
mFTPClient.enterLocalPassiveMode();
mFTPClient.changeWorkingDirectory("/data/forecasts/taf/stations");
InputStream inStream = mFTPClient.retrieveFileStream("KABQ.TXT");
InputStreamReader isr = new InputStreamReader(inStream, "UTF8");
And I also found on the web someplace an answer to the 'byte-by-byte' question. This seems to work to convert an InputStream type directly to String type:
String theStr = new Scanner(inStream).useDelimiter("\\A").next();
I also looked for a simple ftp download example without using of 3rd party libs. Didn't find any, so post my solution here.
URLConnection by default uses user name 'anonymous' with empty password which is not accepted by many ftp servers, as they require e-mail as the password for 'anonymous'.
To use the following code in your app, just add try..catch and make sure that reading from stream isn't block UI thread.
URL url = new URL("ftp://ftp.mozilla.org/README");
URLConnection cn = url.openConnection();
cn.setRequestProperty ("Authorization", "Basic " + Base64.encodeToString("anonymous:a#b.c".getBytes(), Base64.DEFAULT));
final File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
FileOutputStream fos = new FileOutputStream(dir.getPath() + "/README");
InputStream is = cn.getInputStream();
int bytesRead = -1;
byte[] buf = new byte[8096];
while ((bytesRead = is.read(buf)) != -1) {
fos.write(buf, 0, bytesRead);
}
if(is != null)is.close();
if(fos != null){ fos.flush(); fos.close(); }
Hope this will save you some time.

how to find operator name from website phone no. search page in android application?

I need to find operator name from phone no. using this website in my android application.
Requesting and parsing HTML in the application works fine.
When I query request string from the app:
address: .https://nummertjanster.pts.se/net/en/Nummerkapacitet/Enskiltnummer?&_rp/pts.SearchNumber_ndc=70&_rp/pts.SearchNumber_operator=Tele2+Sverige+AB&_rp/pts.SearchNumber_telnumber=4264128
I need to specify 'operator name' ..which is wierd I guess.
The problem is no matter which number (ndc-telnumber) I enter if I specify a operator name in the request string the resulting webpage shows that operator name.
Here are some numbers to test:
073-3355433 = Telenor Sverige AB
073-6107353 = Tele 2 Sverige AB
070-3999266 = TeliaSonera Sverige AB
073-2404070 = Glocalnet AB
How can I find the proper operator name for a specific number?
Thanks for your any help.
There are a couple of issues with the site that prevent things from working:
It needs a cookie for the POST to work.
The operator name is actually not returned as part of the page, it is returned as part of a location redirect (302).
This chunk of code does what you want (I was dodging work, so I actually tidied it up for you): it hits the main page, fetches/extracts the cookie returned, posts the area code and number to the website and then intercepts the Location header and pulls out the operator name. Note that the area code is not always 3-digits (so for example for 073-3355433 you would do String operatorName = findOperator("73","3355433");.
String findOperator(String ndc, String number)
{
String parameters = "action=search&ndc="+ndc+"&number="+number+"&search=S%F6k";
HttpURLConnection httpUrlConnection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
int code = 0;
String response = null;
try {
java.net.URI u = new java.net.URI("https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer");
httpUrlConnection = (HttpURLConnection) u.toURL().openConnection();
httpUrlConnection.setConnectTimeout(7500);
httpUrlConnection.setReadTimeout(7500);
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.connect();
String cookie = httpUrlConnection.getHeaderField("Set-Cookie");
u = new java.net.URI("https://nummertjanster.pts.se/actionrequest/sv/Nummerkapacitet/Enskiltnummer?__ac_/pts.SearchNumber");
httpUrlConnection = (HttpURLConnection) u.toURL().openConnection();
httpUrlConnection.setConnectTimeout(7500);
httpUrlConnection.setReadTimeout(7500);
httpUrlConnection.setRequestProperty("Cookie", cookie);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setDoOutput(true);
httpUrlConnection.connect();
outputStream = httpUrlConnection.getOutputStream();
outputStream.write(parameters.getBytes("UTF-8"));
httpUrlConnection.setInstanceFollowRedirects(false);
try {
inputStream = httpUrlConnection.getInputStream();
} catch (IOException e) {
//andrologger.warn("An error occurred while POSTing to " + url, e);
}
code = httpUrlConnection.getResponseCode();
response = httpUrlConnection.getHeaderField("Location");
if(response != null){
response = response.split("&")[2].split("=")[1];
}
}catch(Exception e1){
android.util.Log.v("Configuration","Exception: "+e1.getMessage(), e1);
} finally {
closeQuietly(outputStream);
closeQuietly(httpUrlConnection);
}
return response;
}
Tested it on my phone and it works fine: let me know how it works for you.
It clearly doesn't work restfully. You'll have to find another way.
Perhaps imitate the form post that the page is doing: http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient
EDIT this doesn't work
Pretty simple:
https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer?&__rp_/pts.SearchNumber_ndc=PUT_AREA_NUMBER_HERE&__rp_/pts.SearchNumber_operator=xxno_operatorxx&__rp_/pts.SearchNumber_telnumber=PUT_NUMBER_HERE
i.e.
https://nummertjanster.pts.se/net/sv/Nummerkapacitet/Enskiltnummer?&__rp_/pts.SearchNumber_ndc=696&__rp_/pts.SearchNumber_operator=xxno_operatorxx&__rp_/pts.SearchNumber_telnumber=1788300

Data from Android App -> SQL server

I'm developing an android application which is to collect data and then send it to a web directory.
So lets say a want to collect an array of data on the phone, and then after clicking a button send it all to the online directory as a file or stream. It does not even need to get a response - although in the future a confirmation would be handy.
Here is a guess at the sort of order of things...
dir = "someurl.com/data/files_received";
Array data;
sendDataSomehow(dir, data); //obv the difficult bit!
I am in very early stages of developing for Android although I have a lot of experience coding web so that bit will be fine.
I have found suggestions for things such as JSON, Google GSON, HTTP POST and GET - do these sound like the right track?
I hope I have been clear enough.
Yep, JSON would be a good solution for this.
Encode your array as JSON and then send it to your web server as the body of an HTTP POST request. If you have an hour to kill, here's a really good video from Google IO last year explaining how to implement a REST client on Android (what you're doing isn't strictly REST-ful, but the calls you make to the server are very similer): http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html
Right, just wanted to do a quick thank for putting me on the right track. Just had one of those THE CODE WORKS EUREKA moments, very happy. I haven't used JSON but I have managed to pass a variable from Android to SQL through a HTTP-POST and little bit of PHP.
I'm sure this is not the recommended ideology for many reasons although for prototype and presentation it will do just fine!
Here is the code for android:
try {
URL url = new URL("http://www.yourwebsite.com/php_script.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream out = conn.getOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
writer.write("stringToPass=I'd like to pass this");
writer.close();
out.close();
if(conn.getResponseCode() != 200)
{
throw new IOException(conn.getResponseMessage());
}
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
conn.disconnect();
} catch (MalformedURLException e1) {
textBox.setText(e1.toString());
} catch (IOException e2) {
textBox.setText(e2.toString());
}
And here is the code for the PHP:
$conn = mysql_connect("localhost","web108-table","********") or die (mysql_error());
mysql_select_db("web108-table",$conn) or die (mysql_error());
$str = $_POST['stringToPass'];
mysql_query("INSERT INTO table(field) VALUES ($str)");
This code works, very simple. Next tests will be to find out if it is suitable for a large number of strings.
I hope this is helpful to somebody else.

Categories

Resources