I want to send data from android to php file which is adding data to mysql database using POST method, i have no idea how i coult bite this.. any help?
I already connected with http by method post.. and no clue what now...
public URL makeUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
public static void HttpConnect(URL url) {
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
//to do
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
PHP FILE with adding by POST method.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
require 'connect.php';
create();
}
function create(){
global $connect;
$name = $_POST["nazwa"];
$ingredients = $_POST["skladniki"];
$price = $_POST["cena"];
$type = $_POST["typ"];
$photo = $_POST["zdjecie"];
$query = "INSERT INTO dania('nazwa','skladniki','cena','typ','zdjecie') VALUES ('$name','$ingredients','$price','$type','$photo');";
mysqli_query($connect, $query) or die (mysqli_error($connect));
mysqli_close($connect);
}
?>
Use Uri.Builder to attach POST payloads and write it on OutputStream,
In Below code, replace YOUR_VALUE1,YOUR_VALUE2,YOUR_VALUE3,YOUR_VALUE4,YOUR_VALUE5 to suitable values which you like to POST it to server.
Also i would recommend this block of code wrapped inside AsyncTask.
Eg.
public static void HttpConnect(URL url) {
StringBuilder stringBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setConnectTimeout(10000);
httpURLConnection.setReadTimeout(15000);
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("nazwa",YOUR_VALUE1);
builder.appendQueryParameter("skladniki",YOUR_VALUE2);
builder.appendQueryParameter("cena",YOUR_VALUE3);
builder.appendQueryParameter("typ",YOUR_VALUE4);
builder.appendQueryParameter("zdjecie",YOUR_VALUE5);
String urlQuery = builder.build().getEncodedQuery();
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTf-8"));
bufferedWriter.write(urlQuery);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
httpURLConnection.connect();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
String line = "";
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line).append("\n");
}
// your json response output is here
Log.d("RESULT",stringBuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
For the Complete example, i have written about AsyncTask in my blog
Related
I m trying to send a Json Post request using my Android Application.
But something weird happens.
Here is my Android Code:
try {
URL url = new URL(BASE_URL + params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect();
//JSonObject
JSONObject json = new JSONObject();
for(int i = 0 ; i < jsonValues.size(); i +=2){
json.put(jsonValues.get(i), jsonValues.get(i + 1));
}
jsonValues.clear();
DataOutputStream output = new DataOutputStream(connection.getOutputStream());
//String encoded= URLEncoder.encode(json.toString(),"UTF-8");
output.writeBytes(URLEncoder.encode(json.toString(),"UTF-8"));
output.flush();
output.close();
int HttpResult = connection.getResponseCode();
if(HttpResult ==HttpURLConnection.HTTP_OK){
BufferedReader br = new BufferedReader(new InputStreamReader(
connection.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
String lineDecoded = URLDecoder.decode(line, "UTF-8");
sb.append(lineDecoded + "\n");
}
br.close();
System.out.println(""+sb.toString());
if(sb != null){
return sb.toString();
}else{
return null;
}
}else{
Log.d("ERRORRRRR",connection.getResponseMessage());
return connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} catch (JSONException e) {
e.printStackTrace();
return e.toString();
}
My php code is this:
$content = file_get_contents("php://input");
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0)
{
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to
application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the incoming RAW post data from JSON.
$decoded = json_decode($content, true);
echo($decoded);
exit;
The $decoded is null when I make a request using my Android application and using json_last_error() function I get JSON_ERROR_SYNTAX.
This is the raw content of the post request:
{"name":"test","identifier":"12345677"}
But I can't understand what is the problem. In fact when I try to use Advance Rest Client to simulate the same request it works perfectly as shown in the picture below.
I finally solved my Problem.. It seems to be the
URLEncoder.encode(json.toString(),"UTF-8");
In fact removing it and sending just output.writeBytes(json.toString());
Everything works perfectly
I am trying to send json data to server using HTTPURLConnection. But every time response id null from server. i tried by POSter also but it is working there.
try {
jsondata ="{\"A\":\"1234\",\"country_code\":\"91\",\"name\":\"sajal\",\"phone_number\":\"88999\"}";
URL url = new URL(uri);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setDoOutput(true);
httpConn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
httpConn.setRequestMethod("POST");
StringBuffer requestParams = new StringBuffer();
if (jsondata != null && jsondata.length() > 0) {
Uri.Builder builder = new Uri.Builder().appendQueryParameter("data", jsondata);
String query = builder.build().getEncodedQuery();
OutputStream os = httpConn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
bufferedWriter.write(query);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
}
InputStream inputStream = null;
if (httpConn != null) {
inputStream = httpConn.getInputStream();
} else {
throw new IOException("Connection is not established.");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
response = reader.readLine();
reader.close();
if (httpConn != null)
httpConn.disconnect();
} catch (UnknownHostException one) {
return response;
} catch (SocketException two) {
return response;
} catch (Exception three) {
return response;
}
return response;
}
Keeping my json string in "data" key
PHP:-
if (isset($_POST['data'])) {
$data = json_decode($_POST["data"], true);
// php code.....
} else {
// control comes here..
// php code.....
}
Here $_POST['data'] is not working. Please check whats wrong in PHP or Andooid code.
(sorry for my bad english)
I have the next code to send data via POST to Server. This code is working in another application correctly. But this does not work now. It's a function that return the response data:
BufferedReader reader = null;
try {
URL url = new URL(path);
HttpURLConnection conecc = (HttpURLConnection) url.openConnection();
conecc.setReadTimeout(5000);
conecc.setConnectTimeout(5000);
conecc.setDoOutput(true);
conecc.setDoInput(true);
conecc.setChunkedStreamingMode(0);
conecc.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("name", name)
.appendQueryParameter("birthday", bithday)
.appendQueryParameter("sex", sex);
String query = builder.build().getEncodedQuery();
OutputStream outputstream = conecc.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputstream, "UTF-8"));
writer.write(query);
outputstream.close();
StringBuilder sbuilder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(conecc.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
sbuilder.append(line + "\n");
}
//writer.flush();
//writer.close();
return sbuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
On the server i just have this (PHP):
print_r($_POST)
But i get an empty array. Then connection to server works but data is not sent.
Array()
I have added these lines before conecc.connect(); unsuccessfully:
conecc.setRequestProperty("Connection", "Keep-Alive");
System.setProperty("http.keepAlive", "false");
conecc.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
conecc.setRequestProperty("Accept", "*/*");
conecc.setRequestMethod("POST");
Have you tried the conecc.setRequestMethod("POST"); ?
From the rest of your class, there seems to be no typos. But to be sure, check that String query = builder.build().getEncodedQuery(); yelds non-null results (just log it, or show as a Toast).
Check this for additional aid in your problem.
EDIT
Check this as well for additional ways to fix your issue.
Since you seem to be brazzilian, post in portuguese in the comments if you cannot writte what you want/need, and we will try to help with that.
I will try to put it simple, from a similar question
URL url = new URL("http://YOUR_URL.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conecc.setReadTimeout(10000);
conecc.setConnectTimeout(15000);
conecc.setRequestMethod("POST");
conecc.setRequestProperty("Accept-Charset", "UTF-8");
conecc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
conecc.setDoInput(true);
conecc.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conecc.connect();
And in that same class:
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
this should be a stupid mistake of mine, please help me figure it out.
I have a app which sends some messages to a php server, using POST, but there is no data,
URL url = new URL("http://192.168.1.2/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
OutputStream outputStream = null;
try {
if (purchase != null) {
outputStream = conn.getOutputStream();
BufferedOutputStream stream = new BufferedOutputStream(outputStream);
stream.write(postmess.getBytes()); // <<<< No effect ?!
stream.flush();
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (outputStream != null)
try {
outputStream.close();
} catch (IOException logOrIgnore) {
// ...
}
}
Log.d(TAG, "data 2 send:" + postmess);
outputStream.flush();
outputStream.close();
// Get the response
int responseCode = conn.getResponseCode();
Log.d(TAG, "Sending 'POST' request to URL : " + url);
Log.d(TAG, "Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// result
Log.d(TAG, "Response:" + response.toString());
in Server:
<?php
echo "POST = " . var_dump($_POST);
here is the log:
PostHTTPS﹕ data 2 send: "this is long text."
PostHTTPS﹕ Sending 'POST' request to URL : http://xx.xx.xx.xx
PostHTTPS﹕ Response Code : 200 // means OK
PostHTTPS﹕ Response:array(0) {}POST = array(0)
I am developing an Android app that should get an image from remote server. Am using WAMP as my server and PHP as programming language. I know how to get text data using JSON.
Am not using blob to store image.
Images have stored in a folder on server. Url of image is stored in db table.
I tried the following snippet, I got this from net but it is not giving any error and also it is not displaying image
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
InputStream instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
String base64Image = jsonObj.getString("pprs");
Toast.makeText(getBaseContext(), base64Image, Toast.LENGTH_LONG).show();
byte[] rawImage = Base64.decode(base64Image, Base64.DEFAULT);
bmp = BitmapFactory.decodeByteArray(rawImage, 0, rawImage.length);
}
}
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
if($row = mysql_fetch_assoc($query))
{
$response = $row['imageUrl'];
}
$response = base64_encode($response);
echo '{"pprs":'.json_encode($response).'}';
mysqli_close($con);
?>
I checked my php code with html(with out encoding $response value) am getting image there, but not in Android.
I am not good with Php, but if you return the file url via a JSON reponse you can use the following code for downloading the file.
int count;
try {
URL url = new URL("http://url of your file");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
## Edit ##
After the Image is downloaded you can create a Bitmap from the Image Path/InputStream and assign it to the Image View like this
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
Bitmap bmp = BitmapFactory.decodeStream(bufferedInputStream);
Original source
try {
httpClient = new DefaultHttpClient();
httpPost = new HttpPost("http://10.0.2.2/sareesProject/returnSareeTypeImageUrls.php");
response = httpClient.execute(httpPost);
entity = response.getEntity();
if(response.getStatusLine().getStatusCode() == 200)
{
Log.d("Http Response:", response.toString());
if(entity != null)
{
instream = entity.getContent();
JSONObject jsonObj = new JSONObject(convertStreamToString(instream));
bitmapPath = jsonObj.getString("pprs");
}
}
try {
Toast.makeText(getBaseContext(), "http://10.0.2.2/sareesProject/"+bitmapPath, Toast.LENGTH_SHORT).show();
URL url = new URL("http://10.0.2.2/sareesProject/"+bitmapPath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
bmp = myBitmap;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
if(bmp == null)
Toast.makeText(getBaseContext(), "null", Toast.LENGTH_SHORT).show();
ImageView imageview = (ImageView) findViewById(R.id.flag);
imageview.setImageBitmap(bmp);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_LONG).show();
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
//new HomePage().show("in con");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
//show(line);
//new HomePage().show("in while");
//new HomePage().show("l="+line);
sb.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(, text, duration)
} finally {
try {
if(reader != null)
{
try{reader.close();}
catch(Exception e){e.printStackTrace();}
}
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}//end of convertStreamToString
The following is my php code
<?php
error_reporting( E_ALL ^ E_NOTICE ^ E_WARNING);
$con = mysql_connect("localhost","root","") or die("con error");
mysql_select_db("sareesdb") or die("db select eror");
$query = mysql_query("select * from noofpiecesinatype");
$response = array();
while($row = mysql_fetch_assoc($query))
{
$response[] = $row['imageUrl'];
}
echo json_encode($response);
mysqli_close($con);
?>
//--------------------
Fnally i got it.............
First of all my server file returns the following
{"pprs":"upload/22.png"}
from this i extracted upload/22.png using JSON
Now bitmapPath contains upload/22.png
Thank you very much to insomniac giving suggestions.............
If it is helpful to any one vote for me..............