Android HttpURLConnection POST not working. - java

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

Related

How to send JSON data to API using HttpsURLConnection on Android?

How can I send JSON data using HttpsURLConnection to my API ?, this is my code
URL endpoint = new URL("https://api.url.com/api/token/");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) endpoint.openConnection();
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("Content-Type", "application/json; utf-8");
myConnection.setRequestProperty("Accept", "application/json");
// Create the data
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
// Enable writing
myConnection.setDoOutput(true);
// Write the data
myConnection.getOutputStream().write(myData.getBytes());
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);}
}
I tried this way, but it doesn't work.
Thank you
Send the request:
String myData = "{\"username\":\"username\",\"password\":\"password\"}";
URL url = new URL ("https://api.url.com/api/token/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
try(OutputStream outputStream = conn.getOutputStream()) {
byte[] input = myData.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
To read the response:
StringBuilder sb = new StringBuilder();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))) {
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line.trim());
}
}
System.out.println(sb.toString());
I hope that helps!

Sending a POST request to a server

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

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.

Java CURL request using HTTP

I am trying to perform a CURL request using Java. The CURL request is as follows:
curl https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1 -u username:password
I am trying to perform the request as follows:
String stringUrl = "https://apis.sen.se/v2/feeds/N4hSBSpFlYzXT6ZN2IA1KadgSR9rTazv/events/?limit=1";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
InputStreamReader inputStreamReader = new InputStreamReader(uc.getInputStream());
and I am trying to see the contents of inputStreamReader as follows:
int data = inputStreamReader.read();
char aChar = (char) data;
System.out.println(aChar);
The code is compiling and running fine, but it is returning nothing. Where am I going wrong?
I ended up getting it working using the following code:
public static void main(String args[]) throws IOException {
String stringUrl = "url";
URL url = new URL(stringUrl);
URLConnection uc = url.openConnection();
uc.setRequestProperty("X-Requested-With", "Curl");
String userpass = "username" + ":" + "password";
String basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
uc.setRequestProperty("Authorization", basicAuth);
StringBuilder html = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String htmlLine;
while ((htmlLine = input.readLine()) != null) {
html.append(htmlLine);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
System.out.println(html.toString());
}
I was also trying to do that thing. I have some kind of workaround but it reads everything it sees.
--Here's the code---
String params = "some-parameters";
URL url = new URL("some-website");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
con.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while((line = reader.readLine()) != null) {
buffer.append(line+"\n");
}
reader.close();
System.out.print(buffer.toString());
--Notice, I use this code to see if a certain account exist on a certain website, since it outputs everything, what I do is to find a specific regularity upon the code which could tell me if that user exist or not. Well I'm not really even sure if this could help you, but it might be. Good Luck...

Sending JSON request to hipchat

I am making something for my HipChat room but for it to work i have to send a JSON request of:
POST /v1/rooms/message?format=json&auth_token=token HTTP/1.1
Host: api.hipchat.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 138
room_id=10&from=Alerts&message=A+new+user+signed+up
So far i have this:
public static void send(String send){
URL url = null;
HttpURLConnection conn = null;
try{
url = new URL("http://api.hipchat.com");
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", "138");
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(
conn.getOutputStream ());
wr.writeBytes (send);
wr.flush ();
wr.close ();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(line);
}catch(Exception e){
e.printStackTrace();
}finally{
if(conn != null) {
conn.disconnect();
}
}
}
But in the console it just returns null. How would i go about sending the above JSON request?
Thanks
Every time you loop here
while((line = rd.readLine()) != null) {
your line variable is replaced with the value returned by rd.readLine(). The last time it loops, that method call will return null. That's why line is null.
I'm going to assume you wanted to print out response.

Categories