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)
Related
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
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
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;
The most confusing question today for all beginners is that how can we make login to user using my sql and php because we find many commands being deprecated. Can somebody explain best way to make a login either be its basicnamevaluepair or httppost or what ever. It will help everybody.
But i tried but didnot work like this
<?php
require "myfile.php";
$username=$_POST['username'];
$userpass=$_POST['password'];
echo 'username is '.$username;
echo 'password is '.$userpass;
$mysql_qry="Select * from employeedata where username like '$username' and password like '$userpass'";
$result=mysqli_query($conn,$mysql_qry);
if(mysqli_num_rows($result)>0)
{echo 'Login Success';
}
else{
echo 'Not success!';
}
?>
Here is myfile.php
<?php
$db_name="employee";
$mysql_username="root";
$mysql_password="";
$server_name="localhost";
$conn=mysqli_connect($server_name,$mysql_username,$mysql_password,$db_name);
if($conn)
{
echo 'Success!';
}
else{
echo 'Not success!';
}
?>
For android i used
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream o = connection.getOutputStream();
InputStream i = connection.getInputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(o, "UTF-8"));
Log.v("adsluser",email);
String postData = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
writer.write(postData);
// writer.flush();
// writer.close();
// o.close();
backresult = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(i, "iso-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
backresult += line;
}
return backresult;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The error i got here is that data didnot get posted in that page. If i set default value and try it is success. Also it is success from browser too.
The error I find here is that you are reading InputStream after opening OutputStream but before posting your data.
Post your data and then only read InputStream because input stream is only expected received after you post data.
Try this
URL url = new URL(myurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream o = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(o, "UTF-8"));
Log.v("adsluser",email);
String postData = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
writer.write(postData);
writer.flush();
writer.close();
o.close();
backresult = "";
InputStream i = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(i, "iso-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
backresult += line;
}
return backresult;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if the goal is simply to do a login, I would suggest leave all of this and go use firebase. Here is the link:
Link to Firebase
It is an amazing tool complete with a database, auth, and much more. I think it is the easiest way to get up and running.
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.