Hi,
i use this class to make a request to server, which consist of the json data object.
Class is:-
public class HttpClient {
private static String URL = "localhost/json/json_handle.php";
public String postJsonData(String data) {
try {
StringBuffer buffer = new StringBuffer();
// Apache HTTP Reqeust
System.out.println("Sending data..");
System.out.println("Data: [" + data + "]");
org.apache.http.client.HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
List<NameValuePair> nvList = new ArrayList<NameValuePair>();
BasicNameValuePair bnvp = new BasicNameValuePair("json", data.toString());
// We can add more
nvList.add(bnvp);
post.setEntity(new UrlEncodedFormEntity(nvList));
HttpResponse resp = client.execute(post);
// We read the response
InputStream is = resp.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
is.close();
buffer.append(str.toString());
// Done!
return buffer.toString();
} catch (Throwable t) {
t.printStackTrace();
}
return null;
}
}
Then i use a php class on server side to get the json object from the request. But, at server side i am getting nothing. Even when i use $_REQUEST method, then code after this method doesn't work.
Here is my php file:-
<?php
$file = fopen("MyFile.txt" ,"w");
$int = $_REQUEST;
fwrite($file,"aaa");
//$input =$_REQUEST['json'];
fwrite($file,"HELLO 111");
//$data = json_decode($input,true);
/*print_r($input);
// get values
$firstname = $input->firstName;
$surename = $input->lastName;
$age = intval($input->age);
// check values
if (isset($firstname) && !empty($firstname) &&
isset($surename) && !empty($surename) &&
isset($age) && is_numeric($age))
{
// do something
echo "Hello ".htmlspecialchars($firstname)." ".htmlspecialchars($surename)."!<br>";
echo "You are $age years old! Wow.";
}
else
{
echo "Some values are missing or incorrect";
}*/
//fwrite($file, $data);
fclose($file);
?>
Any suggestions regarding this problem???
Thanks friends for your help.
I got the solution and now the program is working perfectly on localhost as well as online.
For localhost, we just have to give the URL as:-
1.1.1.1/json/json_handle.php
where 1.1.1.1 is your ip address.
Again, thanks alot friends.
Related
I am a beginner in android development. I want to connect a php file to the android app. My php code is
<?php
$con = mysqli_connect("localhost", "root", "", "invoice_db");
if(mysqli_connect_errno($con)) {
echo "Failed to connect";
}
$response["sucess"]=0;
$invoiceid = $_POST['invc'];
$response = array();
$sql = "SELECT sl_no from invoice_table where invoice_id='$invoiceid'";
$result = mysqli_query($con,$sql);
if(!empty($result)) {
$row = mysqli_fetch_array($result);
$data = $row[0];
$response["sucess"] = 1;
}
mysqli_close($con);
?>
Here 'invc' is get from httpRequest ,
JSONObject json = jsonParser.makeHttpRequest(url_check_user, "POST", params);
And my JSONParser page contains,
if (method == "POST") {
// request method is POST
// defaultHttpClient
System.out.println("Inside json parser POST condition");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
System.out.println("Inside json parser POST condition" + params);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.d("From httpentity", httpEntity.toString());
System.out.println("ppppppppppppphhhhhhhhhhhhhhhhhhhhppppppppppp");
is = httpEntity.getContent();
}
Now I want to check , whether the parameters were passed to the php page or not. So I want to console/log cat the $invoiceid. How can it possible in Eclipse Ide?
If you want to print a variable inside PHP code, you can do echo $variable. However please note that PHP code will be executed on a server and not on your android device. Moreover your PHP code is vulnerable to sql injection attacks
You can use JSON encoding method in your php file to get a proper JSON response like this.
$response = array (
'invoiceid' => $verify_code,
);
print json_encode($response);
which will return a JSON string to your app in a format like
{"invoiceid":"null"}
which you can decode and log it like this
InputStreamReader isw = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isw);
String line = "";
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null){
buffer.append(line);
}
String finalresult = buffer.toString();
JSONObject myobject = new JSONObject(finalresult);
String flag= myobject.getString("invoiceid");
log.e("mylog",flag)
so that it will be visible in your logcat file.
I am currently trying to display an image from mysql database into my android program using an image view. However, it does not work the way I wanted to yet. The following is the php code i currently have:
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT companyImage FROM company where companyID = 2");
$getImage = $image->fetch_assoc();
$upload = $getImage['companyImage'];
header("Content-type: image/png");
echo $upload;
?>
The code displays the image just fine in the browser. The following is my current android code
void getImage() {
//String imageResult = "";
//JSONObject jArray = null;
//String Qrimage;
//Bitmap bmp;
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
imageResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(imageResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
try {
//creates json array
JSONArray jArray = new JSONArray(imageResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
lblTesting3.setText(imageTemp);
byte[] data = Base64.decode(imageTemp, 0);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);
imgCompany.setImageBitmap(b);
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
}
All I have returning is some text that probably has to do with the image I'm returning. The following text is like this in the beginning:
ÿØÿáhExifMM*vž¤¬(1´2Ò‡iè ü€' ü€..... and so on.
Is there a way I can convert this into an image that is displayable into my android program with the code I have or do I have to do something more different? I would appreciate anyone would help me! It would mean a lot! Thanks in advance!
I think the issue you're facing with is a simple decoding mistake.
HttpEntity entity = response.getEntity();
is = entity.getContent();
The InputStream you're getting from the HttpEntity contains binary image data. So you can simply copy that data into an bytearray:
...
Bitmap bitmap;
byte[] image = null;
...
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out, true);
image = out.toByteArray();
in.close();
bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
...
public static void copy(InputStream in, OutputStream out, boolean close)
throws IOException
{
if (in != null && out != null)
{
byte[] buffer = new byte[4096];
int count;
while ((count = in.read(buffer)) > 0)
out.write(buffer, 0, count);
if (close)
{
in.close();
out.close();
}
}
}
I'm trying to encode a .jpg file on my server and send the string back to my android app. The PHP encoding function doesn't seem to be working - I always get a null response.
...
} else if ($tag == 'getPhoto') {
$filePath = $_POST['filePath'];
$filePath = mysql_real_escape_string($filePath);
$photo_str = $db->getPhotoString($filePath);
$photo_str = mysql_real_escape_string($photo_str);
if (!empty($photo_str)) {
echo $photo_str;
} else {
echo 'Something went wrong while retrieving the photo.';
}
}
...
public function getPhotoString($filePath) {
$type = pathinfo($filePath, PATHINFO_EXTENSION);
$photoData = file_get_contents($filePath);
$photo_str = 'data:image/' . $type . ';base64,' . base64_encode($photoData);
// $photo_str = 'test_response';
return $photo_str;
}
I know my filepath is correct because when I change it I get an error that says the file/directory doesn't exist. And, the "test_response" works when I uncomment it. Please help!
UPDATE - relevant android code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
HttpResponse response = httpClient.execute(httpPost);
photoString = convertResponseToString(response);
Log.d("string response", photoString);
public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{
String res = "";
StringBuffer buffer = new StringBuffer();
is = response.getEntity().getContent();
int contentLength = (int) response.getEntity().getContentLength(); //getting content length…..
if (contentLength < 0) {
} else {
byte[] data = new byte[512];
int len = 0;
try {
while (-1 != (len = is.read(data))) {
buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer…..
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close(); // closing the stream…..
} catch (IOException e) {
e.printStackTrace();
}
res = buffer.toString(); // converting stringbuffer to string…..
}
//System.out.println("Response => " + EntityUtils.toString(response.getEntity()));
return res;
}
This is not an answer, only a suggestion but i'm not able to comment as i don't have enough reputation xD. Anyway, did you try to echo $photoData after
$photoData = file_get_contents($filePath);
to see if it's filled with something? Maybe you get a null result. Also, can you tell me what's $filePath value when taken from $_POST variable and when passed to getPhotoString($filePath) function? I'm thinking about something wrong with mysql_real_escape_string().
I am using HttpClient to make a request from my Android device to a simple HTTP server, which contains a PHP script to retrieve a picture. The picture is available inside a blob data. It means if I do this little PHP code in the server side:
file_put_contents("myPicture.png", $blob_data);
I get the picture saved in the server with a file named myPicture.png. Now I want to get this $blob_data (my picture) to save it inside my Android device, not the HTTP server. Someone can give me a hint to return the blob data from the PHP script and get the picture inside the Android device to store it locally?
Here is my HTTPClient:
#Click(R.id.btn_login)
#Background
public void LoginTrigger(){
String nUsername = username.getText().toString().trim();
String nPassword = password.getText().toString().trim();
if (nUsername.matches("") || nPassword.matches("")){
displayToast("Please insert your login!");
}
else{
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("username", nUsername));
urlParameters.add(new BasicNameValuePair("password", nPassword));
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_PROXY);
post.setHeader("User-Agent", SERVER_USER_AGENT);
try{
post.setEntity(new UrlEncodedFormEntity(urlParameters, "utf-8"));
}
catch(Exception e){
Log.getStackTraceString(e);
}
HttpResponse response = null;
try{
response = client.execute(post);
Log.e("Response Code : ", " = " + response.getStatusLine().getReasonPhrase());
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String responseMessage = sb.toString();
checkLogin(responseMessage);
}
catch(Exception e){
Log.e("HTTP-ERROR", " = " + Log.getStackTraceString(e));
displayToast("Check your Internet connection!");
}
}
}
String responseMessage contains my blob data when I echo it in my PHP script. I just need to put this stream inside a Bitmap or something, but I've no clue about how to get it done.
Thanks if you know it!
php code (server)
<?php
header('Content-Type: image/png');
echo($blob_data);
?>
java code (device)
URL url = new URL ("http://myserver.com/myPicture.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (new File(storagePath,"myPicture.png"));
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
Manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You need to change both the client and the server code.
The server code
Add this at the end of your PHP script
header("Content-Type: image/png");
header("Content-Length: " . mb_strlen($blob_data, '8bit'));
echo $blob_data;
exit;
The client code
Your code is not ready to read binary data, please, check out this other question on how to do it: how to download image from any web page in java
it's not recommended to send the actual file to your android app , the best way to do that is by sending a base 64 encoded a link string of the image , which will have all the meta data of the image , then load the image from base46 encoded string
$image = base64_decode($file_path);
return response::json(array('image'=>$image);
and receive it like object and render your image with the base64code image like this
i do it in js like this
var reader = new FileReader();
reader.onload = function(e) {
image_base64 = e.target.result;
preview.html("<img src='" + image_base64 + "'/>");
};
reader.readAsDataURL(file);
I have a problem connecting database with Android app. I am trying to implement this tutorial. Everything seems to be fine but I neither get any success not an error.
There is a button listener which on clicking does a post to a PHP file and gets the result. Here is the code for it:-
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", un.getText().toString()));
postParameters.add(new BasicNameValuePair("password", pw.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://10.0.2.2/check.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("\\s+","");
//error.setText(res);
if(res.equals("1"))
error.setText("Correct Username or Password");
else
error.setText("Sorry!! Incorrect Username or Password");
} catch (Exception e) {
un.setText(e.toString());
}
}
});
Here is the http post method:-
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
Log.d("postMethodReturn", result);
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The PHP code is as below:-
<?php
$un=$_POST['username'];
$pw=$_POST['password'];
//connect to the db
$user = "xyz";
$pswd = "xyz";
$db = "mydb";
$host = "localhost";
$conn = mysql_connect($host, $user, $pswd);
mysql_select_db($db);
//run the query to search for the username and password the match
$query = "SELECT * FROM mytable WHERE user = '$un' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
//this is where the actual verification happens
if(mysql_num_rows($result) --> 0)
echo 1; // for correct login response
else
echo 0; // for incorrect login response
?>
Is there any bug in the program? I tried logging the intermediate values of res (http response) in activity code and result in the execute post method, but nothing is being logged. Tried changing "localhost" to "127.0.0.1" and also into a publicly available webhost, with all the database environment, but no success. All these on emulator and with public host, tried with real device too. Server seems to be running when checked from browser. Database exists with the values. All services running (apache, mysql).
The main problem is that there is no error! Any suggestions what is going wrong?
Couldn't find anyone with the same problem.
the problem was --> in the PHP code. changed it to == or > and everything works fine!