i asked this same question yesterday but i was not too clear about what i wanted the function to do, so i thought that i'd might give it another try!
i want to send data from a java program to a mysql server that i'm currently hosting via a local xampp server. Since this java class is will be used by a code written in android (also swift) it wont be possibe (atleast without a headache) to use a jdbc driver, therefor i'm trying to pass data to a php server with the help of java POST.
The problem is that literally nothing happens when i run the code. no errors, no data is being added to the sql, nothing is happening. So maybe a better programmer than be can have a look at my code and maybe see an issue that i currently can't!
Java code:
public static String main(String x, String y){
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
PHP
<body>
<?php
$db_name = "smoothie";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$usr = $_POST["username"];
$pass = $_POST["password"];
$conn = mysql_connect($server_name,$mysql_username,$mysql_password,$db_name);
$query = "INSERT INTO members (username, password)
VALUES ('$usr','$pass')";
?>
I could really use some help here!! :)
Related
I am trying to create my first android application that utilizes a REST api. My api is written in Node.JS and has already been tested using Postman, however, I am having trouble sending JSON data to my api.
#Override
protected String doInBackground(String... params) {
String data = "";
String urlName = params[0];
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) new URL(urlName).openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params[1]);
wr.flush();
wr.close();
InputStream in = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(in);
int inputStreamData = inputStreamReader.read();
while (inputStreamData != -1) {
char current = (char) inputStreamData;
inputStreamData = inputStreamReader.read();
data += current;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return data;
}
I always reach the line that declares and initializes my DataOutputSteam and doesn't execute the code. I am not even getting a log that my Virtual device has visited my server at all.
I have included in the manifest XML both of these already.
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Based on your logs, you're hitting a NetworkOnMainThreadException and that's preventing the network request from being executed (it's going into your catch block instead). This suggests you aren't calling your AsyncTask correctly - ensure that you're calling execute instead of calling doInBackground. See also here for more information on this general pattern.
Try this, it is for POST method that accept 2 parameter email and password.
Change it based on your requirement
URL url = new URL(Login_url);
HttpURLConnection conn = (HttpURLConnection) new URL(urlName).openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept" , "application/json");
conn.connect();
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", "Your_Email")
.appendQueryParameter("password","Your_Password");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
code = conn.getResponseCode();
Log.e("Result", code + "");
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.e("Result",result.toString());
I recently wrote some code in java that is supposed to send a string to a php script and it works perfectly fine. However it refuses to work when i use it in an android program. thought someone could help me find out what the problem is!
public static String main(String x, String y){
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}else{
try{
String username = x;
String password = y;
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
// LÄSER FRÅN HEMSIDAN
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine()) != null){
result += line;
}
//AVSLUTA CONNECTION
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
}catch(Exception e){
e.printStackTrace();
}
}
return null;
}
I did allow internet permission in the manifest by adding
<uses-permission android:name="android.permission.INTERNET" />
but it simply gives me no result. At first i thought that maybe there was something missing in the php script but it works perfectly fine when being tested in eclipse, so there must be something wrong or missing from the android part, right?
Make sure your else block executes.
That's a VERY bad practice - use Retrofit library for consuming REST apis instead. http://www.vogella.com/tutorials/Retrofit/article.html
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
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.
I have implemented reCaptcha in the application I am working on. Somehow I am getting a blank reCaptcha response.
It works fine with localhost, but I am having a problem in upper environments like DEV, TEST. User response is being verified on server side (servlet).
Anyone having idea or faced similar problem ? Let me know if you need more info.
String userresponse = (String) request.getAttribute("g-recaptcha-response");
URL url = null;
HttpURLConnection conn = null;
String line, outputString = "";
try {
url = new URL(https://www.google.com/recaptcha/api/siteverify?secret=privateKey&response=userresponse);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
outputString += line;
}
Log.debug("Google response is :- "+outputString);
} catch (IOException e) {
e.printStackTrace();
}