POST json data using HttpURlConnection - php

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.

Related

How to send data from android to mysql?

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

BufferedReader UTF-8 BOM

I have a method in Java where I try to get one integer (user id) through a POST json request, this is the method:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
//con.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, "UTF-8")); // ISO-8859-1
in.mark(1);
if(in.read() != 0xFEFF)
in.reset();
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
idUser = object.getInt("id");
}
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
The problem is that the response contains a UTF-8 BOM character, on postman the result it's ok and I can see the id: ({"id":"7","correct":true})
But debugging on android studio I got the value "" or null for idUser, I don't know why, I've tried so many ways to resolve this problem without succeed.
Also on the php server side I've executed echo mb_detect_encoding($idUsuario); and I got ASCII encoding in case that could help to find the solution.
Any help will be apreciated, thank you!
So finally I got the solution, I post it here in case someone have the same issue as me, the problem was with the parameters of the JSON, because they included UTF-8 characters like €, so instead of reading the parameters like this:
wr.writeBytes (urlParameters);
I have to do this:
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
I post also the complete function in case someone needs it:
public static Integer getUserIdOwnerOfMsg(Message msg) {
Integer idUser = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("textMsg", msg.getTextMsg());
jsonObject.put("hourMsg", msg.getHourMsg());
List list = new LinkedList();
list.addAll(Arrays.asList(jsonObject));
String jsonString = list.toString();
String urlStr = SERVER_PATH + "getUserIdOwnerOfMsgJSON.php";
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "your user agent");
con.setRequestProperty("Accept-Language", "sp,SP;q=0.5");
String urlParameters = "json=" + jsonString;
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (con.getOutputStream());
byte[] buf = urlParameters.getBytes("UTF-8");
wr.write(buf, 0, buf.length);
wr.flush();
wr.close();
InputStream instream;
int status = con.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
instream = con.getErrorStream();
else
instream = con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(instream, Charset.forName("UTF-8")),8192);
String inputLine;
StringBuilder response = new StringBuilder();
while((inputLine = in.readLine()) != null)
response.append(inputLine);
JSONObject object = new JSONObject(response.toString());
Boolean correct = object.getBoolean("correct");
if (correct) {
try {
String idUserText = object.getString("id");
idUser = Integer.valueOf(idUserText);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return idUser;
}
That's all, happy coding!

Why is my call to getInputStream() returning an empty html string?

Wondering what the hell is going on and desperately need help.
Am trying to return some JSON from the server and get this instead...
<!doctype html><html><head><meta charset="utf-8><title>Untitled Document</title></head><body></body></html>
So... my code.
Android code:
JSONObject data = new JSONObject();
try {
data.put("showTips", "true");
} catch (JSONException e) {
e.printStackTrace();
}
// Headers
ArrayList<String[]> headers = new ArrayList<>();
headers.add(new String[]{"custom-header", "custom value"});
headers.add(new String[]{"Content-Type", "application/json"});
try{
URL url = new URL("https://www.grinners4winners.com.au/grin1_app_backend/post2.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
for (int i = 0; i < headers.size(); i++) {
conn.setRequestProperty(headers.get(i)[0], headers.get(i)[1]);
}
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setUseCaches(false);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(data));
writer.flush();
writer.close();
os.close();
conn.connect();
int responseCode=conn.getResponseCode();
String responseMessage=conn.getResponseMessage();
JSONObject jsonObject = new JSONObject();
jsonObject.put("status_code", responseCode);
jsonObject.put("status_message", responseMessage);
if (jsonObject.getInt("status_code")< 400) {
// BufferedReader in = new BufferedReader(new InputStreamReader(httpResult.getResponse()));
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String result = "";
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
in.close();
return result;
}else{
return "false: ".concat(String.valueOf(responseCode));
}
} catch (Exception e) {
return "Exception: ".concat(e.getMessage());
}
For testing purposes I've tired to scale back the PHP to the bare necessities removing a bunch of other code and additional $_POST checks and still no luck.
Here's the PHP
<?php
ob_start();
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json;charset=utf-8');
header ('Cache-Control: no-cache, must-revalidate');
header("Expires: Sun, 16 Jul 2017 05:00:00 GMT");
//if ($_POST['showTips']){
$json = json_encode(file_get_contents('./tips.json'));
if ($json===false){
$json = json_encode(array("jsonError",json_last_error_msg()));
if ($json ===false){
$json='{"jsonError":"unknown"}';
}
http_response_code(500);
}
echo $json;
//}
ob_end_flush();
?>
If I punch in the URL in my browser, it echos the contents of tips.json as I'd expect (validated this at JSONLint). Basically, I've got no clue as to what's going on. Cheers for any suggestions.
Stumbled across a brilliant tool (PostMan, ttps://www.getpostman.com/) which massively simplified my Java code. It spat out the following code...
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "showTips=test");
Request request = new Request.Builder()
.url("https://www.grinners4winners.com.au/grn1_app_backend/post2.php")
.post(body)
.addHeader("content-type", "application/x-www-form-urlencoded")
.addHeader("cache-control", "no-cache")
.addHeader("postman-token", "a8529ea3-b9af-38ed-f9cc-322e3e9971e3")
.build();
All I had to do then was just hook into the response as follows. Really simple.
String returnvar = "";
ResponseBody rb;
try {
Response response = client.newCall(request).execute();
rb = response.body();
returnvar = rb.string();
} catch (IOException e) {
e.printStackTrace();
}
return returnvar;

Data getting inserted multiple times - android, php

In my project, I'm sending data from an android device and it is inserted into a database using a php script. But the same data is inserted twice. (please see here)
What is wrong with my code?
Android:
try {
String data=URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(Name, "UTF-8");
data+="&"+URLEncoder.encode("family", "UTF-8")+"="+URLEncoder.encode(Family, "UTF-8");
data+="&"+URLEncoder.encode("city", "UTF-8")+"="+URLEncoder.encode(City, "UTF-8");
data+="&"+URLEncoder.encode("ostan", "UTF-8")+"="+URLEncoder.encode(Ostan, "UTF-8");
data+="&"+URLEncoder.encode("tel", "UTF-8")+"="+URLEncoder.encode(Tel, "UTF-8");
data+="&"+URLEncoder.encode("sef", "UTF-8")+"="+URLEncoder.encode(sef1, "UTF-8");
data+="&"+URLEncoder.encode("bod", "UTF-8")+"="+URLEncoder.encode(bodjeh1, "UTF-8");
data+="&"+URLEncoder.encode("tab", "UTF-8")+"="+URLEncoder.encode(tabgh, "UTF-8");
data+="&"+URLEncoder.encode("img", "UTF-8")+"="+URLEncoder.encode(imgs, "UTF-8");
data+="&"+URLEncoder.encode("imgf", "UTF-8")+"="+URLEncoder.encode(fimage, "UTF-8");
URL link=new URL(MainActivity.url+"/app/order.php");
URLConnection con=link.openConnection();
con.setDoOutput(true);
OutputStreamWriter wrw=new OutputStreamWriter(con.getOutputStream());
wrw.write(data);
wrw.flush();
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb=new StringBuilder();
String l="";
while((l=br.readLine())!=null){
sb.append(l);
}
r=sb.toString();
br.close();
Code for insertion - php
$name=$_POST['name'];
$family_name=$_POST['family'];
$city=$_POST['city'];
$ostan=$_POST['ostan'];
$tel=$_POST['tel'];
$comment=$_POST['sef'];
$bod=$_POST['bod'];
$tab=$_POST['tab'];
$img=$_POST['img'];
$imgf=$_POST['imgf'];
$sql="INSERT INTO `customer_table`(`id`, `name`, `family_name`, `city`, `ostan`, `tel`, `comment`,`bodjeh`,`tabagheh`,`imag_f`,`image`)
VALUES ('','$name','$family_name','$city','$ostan','$tel','$comment','$bod','$tab','$imgf','$img')";
Please use below method to send data to server
First convert your request json into simple map like
Map<String, String> map = new HashMap<>();
map.put("name", Name);.....so on
Then use below method to call the Webservice.
private JSONObject sendRequest(String urlString, Map<String, String> map, String fileKey, File file) {
StringBuilder strData= null;
JSONObject resObj = null;
try {
Log.i("Send request", urlString+"="+map);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(50000);
conn.setConnectTimeout(50000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
if(map == null)
{
map = new HashMap<>();
}
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
for (HashMap.Entry<String, String> entry : map.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
reqEntity.addPart(k, new StringBody(v));
}
if(file != null && !TextUtils.isEmpty(fileKey))
{
FileBody filebody = new FileBody(file, "image/*");
reqEntity.addPart(fileKey, filebody);
}
conn.setRequestProperty("Connection", "Keep-Alive");
conn.addRequestProperty("Content-length", reqEntity.getContentLength() + "");
conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());
OutputStream os = conn.getOutputStream();
reqEntity.writeTo(os);
os.close();
conn.connect();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String sResponse;
strData = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
strData = strData.append(sResponse);
}
}
if(strData != null)
resObj = new JSONObject(strData.toString());
} catch (Exception e) {
e.printStackTrace();
}
return resObj;
}
As your php code you need to do :
$result = mysql_query($sql);
if(count($result) > 0)
{
echo "1";
}else
{
echo "0";
}

Don't send data via POST with HTTURLCONNECTION on Android

(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();
}

Categories