Can't send POST message over Https - java

I have a simple android app that needs to send a message to my PHP server, which will return some data back. I am able to get the data returned from the server, but I can't send any. It's probably something stupid, but I can't figure it out. Note that the url here isn't the real url.
public void addUser(User user, String password) throws Exception {
URL url = new URL("https://someuser.c9users.io/service.php");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// set Timeout and method
conn.setRequestMethod("POST");
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestProperty("op", "adduser");
conn.setDoOutput(true);
conn.setRequestProperty("username",user.getUserName());
conn.setRequestProperty("email",user.getEmail());
conn.setRequestProperty("password", password);
if(user.getBirthDate() != null)
conn.setRequestProperty("birthdate", user.getBirthDate().toString());
if(user.getProfImage() != null)
conn.setRequestProperty("profile_image", "some path to img");
//conn.connect(); if I leave the code it does NoFileFoundException. why?
InputStream is = conn.getInputStream();
String result="";
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += inputLine;
}
}
my php code:
function print_post_get() {
echo "post&get vals: ";
foreach($_POST as $key => $value) {
echo $key.":".$value." \n";
}
foreach($_GET as $key => $value) {
echo $key.":".$value." \n";
}
}
//print all post and get
print_post_get();
//get method form post
if(empty($_POST['op']))
die('no operation?');
switch($_POST['op']) {
case 'adduser':
$retval = adduser();
if($retval) //couldn't add user
echo $retval;
break;
case 'removeuser':
$retval = removeuser();
if($retval)
echo $retval;
break;
case 'getuser':
$retval = getuser();
echo $retval;
break;
default:
echo "unknow op.";
break;
}

I recently had a similar problem. I found setRequestProperty adds to your headers, not the POST body. But the
conn.setDoOutput(true)
allows you to connect to the
outStream = conn.getOutputStream()
Now you can create the POST data with a android.net.Uri.Builder.
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username",user.getUserName())
.appendQueryParameter("email",user.getEmail());
Write to the stream, the getEncodedQuery()
try (OutputStream outStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(outStream, "UTF-8"))) {
String query = builder.build().getEncodedQuery();
writer.write(query);
}
Now you can POST your request with conn.

Related

Proper way to make PHP "POST" statements in Java (Android-Studio)

I'm trying to post two strings on a PHP web server. First, I use this relevant part of my PHP script, which does work in other projects with other languages.
function open($db){
$name = $_POST['name'];
$pwd = $_POST['pwd'];
// Prepare SQL statement
$statement = $db->prepare("SELECT * FROM `table` WHERE `name`=?");
$statement->bind_param("s", $name);
$statement->execute();
$result = $statement->get_result();
$row = mysqli_fetch_assoc($result);
if($result->num_rows > 0){
$hashed_pwd = $row['pwd'];
}
else{
echo 'No result!';
$statement->close();
return;
}
if(password_verify($pwd, $hashed_pwd)){
echo 'Success!';
}
else {
echo 'Wrong password!';
}
// Close SQL Statement
$statement->close();
}
In Java, I face multiple problems. The function gets called, when pressing the “Open” button:
public void onOpenClick(View v){
final String name = "someString";
final String pwd = "someString";
new Thread(new Runnable() {
#Override
public void run() {
try {
//Add the action to the original URL
urlString += "?action=open";
URL url = new URL(urlString);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
String info = "name=" + name + "pwd=" + pwd;
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(info.getBytes("UTF-8"));
con.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
answer = in.readLine();
}catch (Exception e){
System.out.println(e.toString());
answer = e.toString();
}
}
}).start();
}
Is using a Thread the correct way to make a PHP requests?
Furthermore, I always get as answer “No result!” and if I change the echo statement in the PHP file to $name, nothing returns at all.
In conclusion, the connection to my server is successful, the POST statement is not. I tried different approaches, none of them worked.
If I press the button again, I do not get any response at all and answer is null or empty.
Edit
I tried adding following statements as well:
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "utf-8");
And:
StringBuilder postData = new StringBuilder();
postData.append(URLEncoder.encode("name", "UTF-8"));
postData.append("=");
postData.append(URLEncoder.encode(name, "UTF-8"));
postData.append(URLEncoder.encode("pwd", "UTF-8"));
postData.append("=");
postData.append(URLEncoder.encode(pwd, "UTF-8"));
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
con.setRequestMethod("POST");
con.setInstanceFollowRedirects(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
con.setDoOutput(true);
con.setUseCaches(false);
I had the same issue when trying to call a php server from javascript.
I figured out I needed to add the Content-Type header correctly.
'Content-Type': 'application/x-www-form-urlencoded'

Android HttpURLConnection POST not working.

I'm trying to check if a number exists in the database, but am unable to send forward the data from android to php.
Should the data be String, JSON or HashMap? How do I send it?
Java
try {
URL url = new URL("http://192.168.0.106/cei/tourist_home_activities.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setReadTimeout(15*1000);
conn.setConnectTimeout(15*1000);
conn.setRequestProperty( "Content-Type", "application/json" );
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bufferedWriter.write(*Here is where I assume I input data*);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream inputStream = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
response+= line;
}
bufferedReader.close();
inputStream.close();
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
PHP
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_select_db($conn,"discover_ilhabela");
$PIN=$_POST['pin'];
$result = mysqli_query($conn, "SELECT Name FROM `monitors` WHERE `PIN`='$PIN'");
/* if (mysql_num_rows($result)==1)
{
print("1");
}
else
{
print("0");
} */
print($PIN);
?>
I'm trying to check if there is any result to confirm that the number exists in the database, but first I'm just trying to return the string and it's returning as empty.
Your PHP endpoint expects $_POST['pin'] so you should send as plain text. Refer to this: How to add parameters to HttpURLConnection using POST

php java android POST method issue

I have android application that check if in DB exists already the phone number. but always it return "+" even there doesn't exists the phone number, this is my code:
URL url = new URL(URL_CHECK);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("cphone", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(IS, "UTF-8"));
String response = "";
String line ="";
while ((line = bufferedReader.readLine()) != null) {
response += line;
}
bufferedReader.close();
IS.close();
info = response;
return info;
The variable "info" always equals "+". This is my PHP Script:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "registers";
$con = new mysqli($servername, $username, $password, $dbname);
$user_name = $_POST["cphone"];
$sql_query = "select id from users where phone like '$user_name';";
$result = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result) >0 )
{
$row = mysqli_fetch_assoc($result);
$name =$row["id"];
echo "$name";
}
else
{
echo "+";
}
?>
The php script work when instead of $_POST["cphone"] I write example "+37455001100".
The way you POST the value might be wrong. You can refer an answer at https://stackoverflow.com/a/2938787/2435238 on correctly sending parameters.

URLConnection and POST method android

I am trying to make a post request using the reference of this documentation. But the problem is that the PHP developer at the other end is not able to receive the value of the parameter hence is not able to send a proper response. Am I missing something out here.
// Edits ;
I am making a HTTP Post request. As you can seen the code below. I am writing the arguments and parameters (location_id=3) to the outputstream. I have also pasted the code for PHP which i have been using. Now the problem is:
The parameter value ( which is 3 ) is not received at the PHP code so I am getting a response which is surrounded by the else block. So I just want to know if there is an error in the android code or the PHP code
#Override
protected Boolean doInBackground(String... params) {
Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
// /* optional request header */
// urlConnection.setRequestProperty("Content-Type", "application/json");
//
// /* optional request header */
// urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(writeToOutputStream(nameValuePairs));
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
Log.d(Constants.LOG_TAG, " The response is " + response);
return true;
}
else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// Here is the code for writeToOutputStream
public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{
String result="";
boolean firstTime = true;
for(BasicNameValuePair pair : keyValuePair){
if(firstTime){
firstTime = false;
}
else{
result = result.concat("&");
}
result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
result = result + "=";
result = result+ URLEncoder.encode(pair.getValue(),"UTF-8");
}
Log.d(Constants.LOG_TAG," The result is "+result);
return result;
}
// Here is the code for convertInputStream to String
public String convertInputStreamToString(InputStream is) throws IOException {
String line="";
String result="";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null){
Log.d(Constants.LOG_TAG," The line value is "+line);
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
Here is the PHP CODE
<?php
include 'config.php';
header ('Content-Type:application/json');
if(isset($_POST['location_id']))
{
$id=$_POST['location_id'];
$selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
$noRows = mysql_num_rows($selectThemeQuery);
//echo "HI";
if($noRows > 0)
{
$result = array();
while($row = mysql_fetch_assoc($selectThemeQuery))
{
$themeid = $row['theme_id'];
//echo "HI";
$selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
$numRows = mysql_num_rows($selectNameQuery);
if($numRows > 0)
{
while($rows = mysql_fetch_assoc($selectNameQuery))
{
$name = $rows['theme_name'];
$image = $rows['theme_image'];
$result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
}
}
}
//echo json_encode($result);
echo json_encode("Hi");
}
else
{
$data2[] = array('Notice'=>false);
echo json_encode($data2);
}
}
else
{
echo "Not Proper Data";
}
?>
Remove:
urlConnection.setChunkedStreamingMode(0);
You use a buffered writer so it can only buffer instead of write.
To force all been written:
bufferedWriter.write(writeToOutputStream(nameValuePairs));
bufferedWriter.flush();
And then ask for a response code. And don't call a response code a status code.
writeToOutputStream() ??? What a terrible name. That function does not write to an output stream. It justs makes a text string.
For Android, I would suggest using a library like Spring-Android.
Spring-Android contains a RestTemplate class, which is a quite effective REST-Client. For example, a simple POST request would be...
myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );
To create the JSON String, I suggest a library like Jackson, which should work fine on Android, see for example here. Not sure if Jackson integrates as fine in Spring-Android as it does in Spring-Web, but in any case, using it to create the Json Strings manually should work just fine.
for post method
create a string builder first
StringBuilder strbul=new StringBuilder();
then append the data like
strbul.append("name=sangeet&state=kerala");
then write to output stream like
httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));
php script will recieve that data on
$_POST['name'] and $_POST['state']

Sending two values into php webpage with java

I am trying to send two string values from my java program into my php page and i seem to be having some difficulty figuring out how this all works.
public static void main (String args[]) throws IOException{
Scanner input = new Scanner (System.in);
String sampleValue = input.next();
String sampleValue1 = input.next();
URL url = new URL("http://woah.x10host.com/randomfact.php");
String result = "";
String data = "fName=" + URLEncoder.encode(sampleValue, "UTF-8");
String id = "lName=" + URLEncoder.encode(sampleValue1, "UTF-8");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// Send the POST data
DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
dataOut.writeBytes(id);
dataOut.writeBytes(data);
dataOut.flush();
System.out.println("Data has been posted");
dataOut.close();
BufferedReader in = null;
try {
String line;
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = in.readLine()) != null) {
result += line;
}
} finally {
if (in != null) {
in.close();
}
}
} finally {
connection.disconnect();
System.out.println(result);
}
}
}
my PHP code is
<?php
$conn = mysqli_connect("localhost","woahx10h_funfact","spk","woahx10h_woah");
// CHECK CONNECTION
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$value_data = $_POST['fName'];
$value_id = $_POST['lName'];
echo $value_data;
echo $value_id;
$conn->close();
?>
However, every time i run the java program, values from both data and id seem to be stored in the $value. I want the value from data to be stored in $value_data while the value from x to be stored in $value_id
You have to add ampersand (&) between each two parameters. So in this case all you have to do is edit your code like this:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
...
If you would want to add another parameter to the request you would have to add another ampersand and then the parameter, for example:
...
dataOut.writeBytes(id);
dataOut.writeBytes("&");
dataOut.writeBytes(data);
dataOut.writeBytes("&");
dataOut.writeBytes(parameter3);
...

Categories