Chunked Steam error in android HTTP post - java

I'm working on creating an android app that will pull down user data from a MySQL database stored on a web server. I've read a few tutorials on HTTP Post that allows me to connect to the database, which I got working. However, I am unable to process the data that gets sent from the php.
The error I receive is: org.apache.http.MalformedChunkCodingException: Chunked stream ended unexpectedly.
This is the code I have written:
String name = username.getText().toString(); //username is a TextView field
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("user",name));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(location);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
Log.e("log_tag", "Error in http connection"+e.toString());
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.i("log_tag", result);
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
Log.e("log_tag", e.toString());
}
The error seems to appear in the convert response to string section. I've looked up several issues regarding similar errors to the one I received but what I read didn't seem to help much or I just don't know enough about http client coding...probably the latter. Any help would be greatly appreciated, thanks!
Here is the PHP as well:
<?php
$con = mysqli_connect("/**connection*/");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM userNames WHERE user='".$_POST['name']."')";
if ($result == NULL)
{
die();
}
else
{
//TODO:get row to java
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
print json_encode($rows);
mysql_close();
}
mysqli_close($con);
}
?>
The end goal of this is to convert the JSON response from the database into separate variables, the buffered reader stuff is just a middle step before the JSON conversion. Again , I just followed a tutorial so if anyone knows a different way of going about this I'm open to suggestions.

Related

Java Php connection error retrieving information from database

I am new to using PHP and Java. I am making a Android app and I got an SQL syntax error...
The Error:
returned to Java:
check the manual that corresponds to your MySQL server
version for the right syntax to use near '#mail.com' at line 1. Any idea how I have to fix that.
I think that a problem of php script. How can I fix this. Any help is greatly appreciated
// Login by email and password if access success setId()
// Saved Email as static string "staticEmail" and used to get CustomerID from customer table
// Get & set CustomerID to "string qr_id" if email=".$email
/* error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near '#mail.com' at line 1
*/
<?php
//connect to MySQL database
mysql_connect("localhost","name","pass") or die(mysql_error());
mysql_select_db("tls_db");
$output = array();
if (isset($_GET['email'])){
$email = $_GET['email'];
$sql = mysql_query("select CustomerID from customer where email=".$email) or die(mysql_error());
while($row=mysql_fetch_assoc($sql)){
$output[] = $row;
}
mysql_close();
print(json_encode($output));
}
?>
Java:
private void setId() {
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://"+URL+"/tls_db/log.php?email=" + staticEmail); //Post email 123#mail.com
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
is.close();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
// Get CustomerId and set to (static string qr_id)
qr_id = json_data.getString("CustomerID");
}
} catch (JSONException e1) {
//iv.setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Server Data Error",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
// Open class QRcode
Intent iSuccess = new Intent(Login.this, QRcode.class);
startActivity(iSuccess);
}
You need to quote your $email in SQL query:
$sql = mysql_query("select CustomerID from customer where email='".$email."'") or die(mysql_error());
Btw, your code is vulnerable to SQL Injections. Make sure to read how to protect from this vector of attack.

Having some trouble connecting an android app to an online database

I have been running into some issues with a small Android project for school. I need to request a password from an online database via a .php by sending it the username. It should return an encrypted password. But there seems to be something wrong with the method I use to connect to the database and receive the password. LogCat gives me these:
Error in HTTP connection java.net.UnknownHostException: boekenapp.atwebpages.com
Error converting result java.lang.NullPointerException
Error parsing data org.json.JSONException: end of input at character 0 of
So my question: What did I do wrong?/What do I need to change to make it work?
The code:
public static String phpconnect(String name, String value) {
String result = "";
InputStream is = null;
//variables to send to database
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair(name,value));
//HTTP post
try{
HttpClient httpclient = new DefaultHttpClient();
URI connection = new URI("http://boekenapp.atwebpages.com/phpscript.php");
HttpPost httppost = new HttpPost(connection);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in HTTP connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
} catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse JSON data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","userid: "+json_data.getInt("userid")+", password: "+json_data.getString("password"));
}
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return "";
}
The second try block will always execute, as you only log in the first catch block.
You should consider a return statement or a throw statement. An alternative is to embed the second try block inside the first one, but that's less readable maybe.
In your case, the problem is that the connection itself fails. Are you sure you have network up ? Can you ping the host from your computer and from Android (you can use adb shell ping <host> on CLI).
And don't truncate the error stacks on their first line, a stack has to be read fully, top-down until you find your piece of code that is causing the bug.
First of all the URL from this code used in a browser redirects to www.alotspace.com/error-404/ Just so you know.
Without testing, just looking at the code, I would start with checking the status line of the response. This is how
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// here all is OK, you can check for 404 and so on
}
Also I see you handling the response with a buffered reader putting everything in a StringBuilder further in code. A better alternative would be using gson.
But focus on the initial network related exception first. The other exceptions are just a result of the separate try/catch blocks (as #Snicolas pointed out already). Unknownhost sounds like no network. Being redirect would just return different output than expected, not unkownhost. To verify that browse to the url from your android device you're testing on.

Cannot bring data fro a URL using httpost request Android

I am having serious trouble on fetching my data from the server.
My url is this:
server_url = http://serverurl/_all
If I call that from my browser, I can see the data being printed. So I guess it has to do with how I make the request. I have used that part of code before, when making a post request for example in a php file. But now my server is setup differently and I know that the server works fine because I can fetch my data in the browser and in an IOS app.
I have tried this:
try {
HttpClient httpclient = new DefaultHttpClient();
#SuppressWarnings("deprecation")
//HttpPost httppost = new HttpPost(URLEncoder.encode(server_url));
HttpPost httppost = new HttpPost(server_url);
//httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
System.out.println("Result:" + result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
and I get this:
Result : Error 404 not found
Then, searching on the SO I have tried the following:
Remove the http://
change the HttpPost line into this
HttpPost httppost = new HttpPost(URLEncoder.encode(server_url));
In this case I get this error:
12-01 21:41:11.772: E/log_tag(28340): Error in http connection java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://ec2-54-194-95-194.eu-west-1.compute.amazonaws.com/backend2/index.php/skicenter/_all
12-01 21:41:11.772: E/log_tag(28340): Error converting result java.lang.NullPointerException: lock == null
12-01 21:41:11.772: E/log_tag(28340): Error parsing data org.json.JSONException: End of input at character 0 of
There should be something wrong with the _ character os something else that I am missing.
Can you help me on that?
Are you sure, you are using the correct HTTP verb for the request? Maybe it's a GET request and you are trying with POST.

Dynamically change mysql query in php with java (android)

I'm using a MySQL database and php for my java/android app.
I haven't got any experience with php.
this is my php file (getAllDataFromSomeTable.php)
<?php
mysql_connect("someHosturl","someUsername","somePassword");
mysql_select_db("databasename");
$q=mysql_query("SELECT * FROM sometable");
while($e=mysql_fetch_assoc($q))
$output[]= $e;
print(json_encode($output));
mysql_close();
?>
and i work with HttpPosts and stuff like that in Java.
This way i can get all the data from 'sometable'
but if i want to use a different query like "select top 1 from sometable where username = 'thisuser'" for example. How can i change that dynamically in java?
How should my php file look and how should the code in java look?
this is the code i have now:
String result = "";
List<? extends NameValuePair> licenses = (List<? extends NameValuePair>) new ArrayList<DriversLicense>();
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://some-url.com/getAllDataFromSomeTable.php");
httpPost.setEntity(new UrlEncodedFormEntity(licenses));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.d("httpclient tag", e.getMessage());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("result is", result);
}catch(Exception e){
Log.d("log-tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.d("from jsonObject", "id= " + json_data.getInt("Id") + ", number = "
+json_data.getString("Number"));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Why don't you try adding parametes to the request?
For example:
http://some-url.com/getAllDataFromSomeTable.php?table=difftable&whereField.1=username&whereValue.1=xyz&whereField.2=surname&whereValue.2=Smith
This way you would need to parse these parameters and build a query based on the passed data.
I'm thinking that the above request would make this query:
select * from difftable where username = 'xyz' and surname ='Smith'
On the other hand, this is what webservices are for, so i would think about something like that, if possible.

how to insert data into server database with user input?

currently, i retrieve data from database is like that
private void getdatafromphp(){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/video.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
json_data = jArray.getJSONObject(jArray.length()-1);
url=json_data.getString("VideoUrl");
}catch(JSONException e1){
}catch(ParseException e1) {
e1.printStackTrace();
}
}
with this php
<?php
mysql_connect("localhost","root","");
mysql_select_db("imammuda");
$sql=mysql_query("select * from Video");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
now i want insert data into database. how to do that?
I had found the sql command which is "insert into table (column1, column2) values ('value1', 'value2')".
This is insert with constant values which is type in php.
What i want is from java there get input from user then copy this input into php 'value1' after that run the php to update the database.
Depending on whether you are using Get or Post
i will assume GET
$value = $_GET['value']; // this will retrieve the value from the url and save it in a variable
mysql_connect("localhost","root","");
// escape the value first
$value = mysql_real_escape_string($value);
mysql_select_db("imammuda");
$result = mysql_query("insert into Video (value) values ('$value')");
?>
learn more about working with the db here
UPDATE
to know the correct request method you can use this.
$req;
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$req = $_GET;
}else {
$req = $_POST;
}
now you can use $req as your request variable:
$value = $req['value'];

Categories

Resources