POST data sent from android app not being received by PHP file - java

I am trying to send data (a student id#) from an Android app to a PHP file via the body of an HTTP POST request. Then the PHP file will send data (just a string for now) back to the app. However, my php doesn't seem to be able to read my POST data (student id#) from the request.
My .java file:
JSONObject jsonParam = new JSONObject();
DataOutputStream printout;
String idIN = params[0];
jsonParam.put("id_in", idIN);
BufferedReader input;
String result;
URL url = null;
HttpURLConnection urlConnection = null;
url = new URL("http://10.0.2.2/project/connector.php");
urlConnection = (HttpURLConnection) url.openConnection();
//prepare request
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
printout = new DataOutputStream(urlConnection.getOutputStream ());
//printout.write(jsonParam);
printout.writeUTF(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
//this returns: {"id_in":"1010101"}
Log.d("json out: ", jsonParam.toString());
printout.flush();
printout.close();
int response = -1;
response = urlConnection.getResponseCode();
input = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
result = input.readLine();
// This returns 200
Log.d("response code: ", result);
urlConnection.disconnect();
MY .PHP FILE:
<?php
header('Content-Type: text/html; charset=utf-8');
$id_in = "";
echo "test1";
$id_in = trim($_POST['id_in']);
echo "test2";
if (isset($_POST['id_in'])) {
echo "good";
}else{
echo "bad";
}
mysqli_close($myconn);
My Android app is receiving a 200 response code and is receiving "test1" in the response, but not "test2", so the problem must be occuring when my PHP file tries to read the POST data: $id_in = trim($_POST['id_in']);

don't forget to use urlConnection.connect();

Related

Spring Boot : POST request returns 401 HttpUrlConnection

I'm using HttpURLConnection to send a POST request to get the access token. However, I get the error says
java.io.IOException: Server returned HTTP response code: 401 for URL: https://xyz.auth0.com/oauth/token
Note: I'm able to get the access token via Postman.
Can someone please help me? Thanks in advance!
public String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://xyz.auth0.com/oauth/token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod(TokenConstant.METHOD_POST);
//set the request content-type header parameter
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "grant_type=client_credentials&client_id=xyz&client_secret=abc&audience=https://xyz.abc.com}";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}
Sample curl facebook oauth access token generation (GET request) - To generate an app access token:
curl -X GET "https://graph.facebook.com/oauth/access_token
?client_id={your-app-id}
&client_secret={your-app-secret}
&grant_type=client_credentials"
Commented few headers - Not required. Changed request to GET.
NOTE: if it works fine with curl, then your code might work fine, with few modifications.
public static String requestToken() throws Exception{
StringBuilder response = new StringBuilder();
URL url = new URL("https://graph.facebook.com/oauth/access_token");
//open a connection
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
//set the request method
connection.setRequestMethod("GET");
//set the request content-type header parameter
// Commented - not required
/*connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("charset", "utf-8");*/
//set response format type
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
//create request parameter
String jsonInputString = "client_id=<your-app-id>&client_secret=<your-app-secret>&grant_type=client_credentials";;
// we need to write it
try(OutputStream outputStream = connection.getOutputStream()){
byte[] input = jsonInputString.getBytes("utf-8");
outputStream.write(input, 0, input.length);
}
//Read the response from Input Stream
//get the input stream to read the response content
try(BufferedReader br = new BufferedReader(
new InputStreamReader(
connection.getInputStream(),"utf-8"))){
String responseLine = null;
while((responseLine = br.readLine()) != null){
response.append(responseLine.trim());
}
}
return response.toString();
}

JSON POST Data via HttpURLConnection

I am trying to make a request to my RESTful API using Android and HttpURLConnection. The data must be sent in the JSON format via POST data.
Here is my code:
JSONObject check_request = new JSONObject();
check_request.put("username", username);
JSONObject request = BuildRequest(check_request, "username_check", false);
Log.i("DEBUG", request.toString());
// DEBUG OUTPUT: {"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}
URL request_url = new URL(apiURL);
HttpURLConnection connection = (HttpURLConnection)request_url.openConnection();
connection.setRequestProperty("User-Agent", "TheGameApp");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
OutputStream os = connection.getOutputStream();
os.write(request.toString().getBytes("UTF-8"));
os.flush();
InputStream in = new BufferedInputStream(connection.getInputStream());
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
String str;
while ((str = br.readLine()) != null)
{
result += str;
}
Log.i("DEBUG", result);
//JSONObject result_json = new JSONObject(result);
os.close();
in.close();
connection.disconnect();
You can see the Debug output as a Comment. The Problem is that the API does not receive any POST data. I have used PHPs var_dump to dump $_POST and $_REQUEST which both are empty arrays.
What am I missing here?
As the question popped up if the API work. This cURL command works fine with the correct result (it is the same JSON data as the debugger printed):
curl -d '{"timestamp":1526900318,"request":{"username":"blubberfucken","type":"username_check"}}' -H "Content-Type: application/json" -X POST http://localhost/v1/api.php
Just for the sake of completeness: The example above is working. The solution to the problem was pa part in PHP on the server side, where I checked the content type and used strpos to search for application/json in $_SERVER['CONTENT-TYPE'] and switched the needle and haystack (thus searching for application/json; charset=UTF8 in the string application/json instead of the other way around).

how to send push notification to the android device using FCM by java server?

I have write this code for send notification using fcm by java server code. But it is throwing exception Server returned HTTP response code: 500 for URL: https://fcm.googleapis.com/fcm/send
public static void pushFCMNotification(String userDeviceIdKey) throws Exception{
String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;
URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");
JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title"); // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + json);
System.out.println("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();
/*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();*/
}
According to the oficial documentation:
Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.
source: https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream
However, make sure that the JSON request is properly formatted. Try to update your question with the json.toString() and check that your API key is still valid using the procedure described in: Checking the validity of a server key

Send http post request to URL with query string using HttpPost client in java

I need to send a post request to url which is formed as follows:
www.abc.com/service/postsomething?data={'name':'rikesh'}&id=45
Using HttpPost client in java, how can post request to such query strings
I could connect from javascript easily through ajax but from java client, it's failing.
(I know sending querystring in post request is stupid idea. Since I am connecting to someone else's server I cannot not change the way it is)
Here is one way to send JSON in a POST request using Java (without Apache libraries). You might find this helpful:
//init
String json = "{\"name\":\"rikesh\"}";
String requestString = "http://www.example.com/service/postsomething?id=45";
//send request
URL url = new URL(requestString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes());
os.flush();
int responseCode = conn.getResponseCode();
//get result if there is one
if(responseCode == 200) //HTTP 200: Response OK
{
String result = "";
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output;
while((output = br.readLine()) != null)
{
result += output;
}
System.out.println("Response message: " + result);
}

Java HTTP POST request (JSON) to PHP server

I have an application (Java) that needs to send json to a php web service.
This is my method to send User in JSON :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection)obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
con.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.flush();
}
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
And my php code :
$string=$_POST['json'];
I tried to insert in my database but $_POST['json'] does not exist.
I didn't see you to posting anything. Add this to your code:
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
This is not right:
con.setRequestProperty("json", json);
setRequestProperty is not used to set the HTTP payload. It is used to set the HTTP headers. For example, you should set the content type accordingly anyway. Like this:
con.setContentType("application/json");
The actual data that you are going to post goes into the HTTP body. You just write it to the end of the stream (before flush):
Here it depends on your implementation on the web server if the data needs to be escaped. If you read the body of the post and interpret it as JSON straight away, it does not need to be escaped:
wr.write(json);
If you transmit one or more JSON strings through parameters (which it looks like, since you are parsing it on the server like $_POST['json']), then you need to url-escape the string:
wr.write("json=" + URLEncoder.encode(json, "UTF-8"));
Im not very familiar with php. You might need to url-decode the string on the server before processing the received json-string any further.
Thx for your help.
This works :
public void login(User user) throws IOException {
Gson gson = new Gson();
String json = gson.toJson(user);
System.out.println(json);
String url = "http://localhost/testserveur/index.php";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("json", json);
OutputStream os = con.getOutputStream();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
//wr.write(new String("json=" + json).getBytes());
String param = "json=" + URLEncoder.encode(json, "UTF-8");
wr.write(param.getBytes());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
}
PHP :
$string=$_POST['json'];

Categories