Java how to send special character is post - java

Im trying to send a post to a backend API from android and this is what I have but some special characters relating to application/x-www-form-urlencoded content type wont be sent or cause problems. Im wondering if there is a way to send the special characters in this format? (+,&) I'm attempting to send the message "This is a message + a test" but my database is getting "This is a message a test"
I've tried passing JSON but the backend that my co-students wrote doesn't accept JSON and returns a 401 not authorized error.
public void sendMessage() {
if(!mEdit.getText().toString().trim().matches("")) { //Cant send empty strings
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(Sendurl); //Create URL
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //Create a Connector
conn.setRequestMethod("POST"); //Dictate the Method
conn.setRequestProperty("Content-Type", "application/json; utf-8"); //Some other properties
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
//This part causes a 401 error because it is the equivalent of passing parameters but our backend uses body formatting
JSONObject jsonParam = new JSONObject();
Date date = new Date();
RequestParams params = new RequestParams();
params.put("username", "admin");
params.put("sessionID", 1);
params.put("cardNum", 111111111);
params.put("sentByStaff", "false");
params.put("message", "This is the message + a test");
params.put("time", date.getTime()/1000);
Log.i("JSON", params.toString());
// OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream()); //Prepare the connection for output
POST_PARAMS = params.toString(); //Converts post parameters to body type
System.out.println(POST_PARAMS);
try(OutputStream os = conn.getOutputStream()) {
byte[] input = POST_PARAMS.getBytes("utf-8");
os.write(input, 0, input.length);
os.flush();
os.close();
}
//os.write(POST_PARAMS); //Write our parameters to the post
//os.flush(); //Do the thing
//os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode())); //Debug
Log.i("MSG", conn.getResponseMessage()); //Debug
int responseCode = 0; //get response code
responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { //On success
mEdit.setText("");
}
conn.disconnect(); //disconnect after attempting post
getMessage(); //update our messages
} catch (Exception e) { //dirty catch all
e.printStackTrace();
}
}
});
thread.start();
}
}

Related

How to send a proper post request to WHMCS installation from android app?

I am trying to send an AddClient post request to my WHMCS installation through my android app but it keeps returning "result=error;message=You did not enter your first name".
I get it to authenticate successfully but it doesnt seem to be posting the jsonObject I am sending it.
Here is a link to WHMCS api documentation: https://developers.whmcs.com/api-reference/addclient/
public void createWHMCSUser(final String emailID, final String random, final String uid) {
final String AccessUserKey = "abc123";
final String AccessKey = "abc123";
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://whmcs.installation.com/includes/api.php?action=AddClient&username=abc123&password=abc123&accesskey=abc123");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept","application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("action", "AddClient");
jsonParam.put("identifier", AccessUserKey);
jsonParam.put("secret", AccessKey);
jsonParam.put("firstname", "User");
jsonParam.put("lastname", "Name");
jsonParam.put("email", emailID);
jsonParam.put("address1", "na");
jsonParam.put("city", "na");
jsonParam.put("state", "na");
jsonParam.put("postcode", "00000");
jsonParam.put("country", "US");
jsonParam.put("phonenumber", "0000000000");
jsonParam.put("password2", random);
jsonParam.put("repsonsetype", "json");
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
//os.writeBytes(jsonParam.toString());
os.flush();
os.close();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
It should return "result=success".
But actually returns "result=error;message=You did not enter your first name".
It’s seems your API doesn’t work in this sample.
try Postman and if json doesn’t work there, issue is in your api.

Java Android FCM sending message to user Server returned HTTP response code

I did this :
public class PushNotifictionHelper {
public final static String AUTH_KEY_FCM = "AIzaSyD63pfTvnwhe9WVuIe.........";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static String sendPushNotification(String deviceToken)
throws IOException, JSONException {
String result = "";
URL url = new URL(API_URL_FCM);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", deviceToken.trim());
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body"); // Notification
// body
json.put("notification", info);
try {
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = "OK";
} catch (Exception e) {
e.printStackTrace();
result = "BAD";
}
System.out.println("GCM Notification is sent successfully");
return result;
}
public static void main(String [] args){
try {
PushNotifictionHelper.sendPushNotification("ep51x3Ckmig:APA91bG4PdoJC7zGlV0JPmCA49jmqJCkeSPH1QzF9byxdH1nRlFOVyAi9ppO2ygoSpp8s44o1oGO8n-HCJDB_oZAZ6WCwFD2a9yAFmKIpKhmPXakeLf-ktqPnzwf-GFziv7_nMdVPIci");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
And when I run this in console I see
java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send
an AUTH_KEY_FCM I get from web from this:
Klucz interfejsu Web API AIzaSyD63pfTvnwhe9WVuIe.........
The 401 error refers to an Authentication error. From the docs:
The sender account used to send a message couldn't be authenticated. Possible causes are:
Authorization header missing or with invalid syntax in HTTP request.
Invalid project number sent as key.
Key valid but with FCM service disabled.
Request originated from a server not whitelisted in the Server key IPs.
Check that the token you're sending inside the Authentication header is the correct Server key associated with your project. See Checking the validity of a Server key for details.
When using FCM, you should always make use of the Server Key (not the Web API Key) seen in the Cloud Messaging Tab in your Firebase Console.

Unexpected status line when making post request from android device

Hi I have an Android app that needs to connect to an API (currently running locally) to authenticate the user, so I'm trying to send a POST request with a JSON object as the request body but whenever I try to login I get the following error:
Unexpected status line: ��
java.net.ProtocolException: Unexpected status line: ��
Here's my code:
String API_URL = "http://10.0.2.2:8443/api/";
try {
URL url = new URL(API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("customerId", 1);
jsonObject.put("password" , mPassword);
jsonObject.put("username" , mEmail);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
Log.d("REQUEST BODY", jsonObject.toString());
wr.flush();
wr.close();
int response = urlConnection.getResponseCode();
Log.d("RESPONSE", String.valueOf(response));
if(response == HttpURLConnection.HTTP_OK) {
InputStream bis = new BufferedInputStream(urlConnection.getInputStream());
return getStringFromInputStream(bis);
}
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
Can anyone please tell me what I might be doing wrong? Thanks!
EDIT
Not sure if this helps but the problem seems to occur when I call urlConnection.getResponseCode();.
Possibly you are recycling the connection
try adding urlConnection.setRequestProperty("Connection", "close"); before connecting

How to display android POST string on PHP server?

I am trying to send json string from my android app to my php server. Below is the complete code from my mobiledb_control.php and httpconnect.java
The Log.v("HTTPSENDER","WORKED"); runs, and I get no errors.
However my error_log("in"); does not run.
How do I display the JSON sent via android into my error_log() ?
HttpConnect.java:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
}catch(Exception e){
e.printStackTrace();
}
}
}
mobiledb_control.php:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/error.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
$headers = apache_request_headers();
?>
try this in PHP code
and turn on error reporting like this
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
and
print_r($_POST);
for more clarification what you are getting from post.
use encode and decode functions of php for making and parsing json.
$request=json_decode($_POST['json']); // it gives the Array
foreach($request as $values){
echo($values['your_value1'])
echo($values['your_value2'])
}
please refer this url : http://php.net/manual/en/function.json-decode.php
Seemed to have fixed it but I have no idea how
PHP File:
<?php
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set("error_log", "../Logs/location.log");
error_reporting(E_ALL);
if(!empty($_POST['json'])){
echo(var_dump($_POST['json']));
error_log($_POST['json']);
}
?>
JAVA File:
public class HttpConnect {
public HttpConnect(){
}
public void sendData(String jsonObject){
try{
URL url = new URL("http://www.alextanti.net/PHPDashboard/Backend/mobiledb_control.php");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
output.write("json="+jsonObject);
output.flush();
output.close();
Log.v("HTTPSENDER","WORKED");
Log.v("HTTPSENDER",""+conn.getResponseCode());
}catch(Exception e){
e.printStackTrace();
}
}
}
In designing server-client communication, it is imperative to make sure both client and server can communicate with each other. With that in mind, can you please provide the server response code by adding this in your code inside try block:
try {
...
Log.d(TAG, "code: " + conn.getReturnCode());
InputStream is = conn.getInputStream();
String serverReply = readIt(is, 500);
Log.d(TAG, serverReply);
...
}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
It will return 200 and 401 respectively. Returns -1 if no code can be
discerned from the response (i.e., the response is not valid HTTP).
Cheers!

Parse.com REST API Error Code 400: Bad Request from Java HTTP Request to Cloud Function

I have a string that I am trying to send to a Parse.com cloud function. According to the REST API documentation (https://www.parse.com/docs/rest#general-requests), it must be in json format, so I made it into a json object and converted it to a string to append to the end of the http request url.
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
String urlParameters = jsonParam.toString();
Then I send the request as so, in my attempt to match their cURL code example as Java code:
con.setDoOutput(true);
DataOutputStream wr = null;
wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Nonetheless, I receive a returned error code of 400 with error message "Bad Request", which I believe to be caused by unrecognizable parameters being sent to the cloud function. None of the other errors in my code trigger. Yet I verified through console logs that emailId is a normal string and the resulting JSON object, as well as its .toString() equivalent comes out as a proper string reading of a JSON object. Also this worked for another function I have in which I am creating an object in my Parse database. So why would it not work here?
Here is the full function for reference and context:
private void sendEmailWithParse(String emailId) throws IOException {
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
HttpsURLConnection con = null;
try {
con = (HttpsURLConnection) obj.openConnection();
} catch (IOException e) {
System.out.println("Failed to connect to http link");
e.printStackTrace();
}
//add request header
try {
con.setRequestMethod("POST");
} catch (ProtocolException e) {
System.out.println("Failed to set to POST");
e.printStackTrace();
}
con.setRequestProperty("X-Parse-Application-Id", "**************************************");
con.setRequestProperty("X-Parse-REST-API-Key", "************************************************");
con.setRequestProperty("Content-Type", "application/json");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
System.out.println("parameter being sent to cloud function: " + jsonParam);
System.out.println("parameter being sent to cloud function as string: " + jsonParam.toString());
String urlParameters = jsonParam.toString();
// Send post request
con.setDoOutput(true);
DataOutputStream wr = null;
try {
wr = new DataOutputStream(con.getOutputStream());
} catch (IOException e1) {
System.out.println("Failed to get output stream");
e1.printStackTrace();
}
try {
wr.writeBytes(urlParameters);
} catch (IOException e) {
System.out.println("Failed to connect to send over Parse object as parameter");
e.printStackTrace();
}
try {
wr.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.close();
} catch (IOException e) {
System.out.println("Failed to connect to close datastream connection");
e.printStackTrace();
}
int responseCode = 0;
try {
responseCode = con.getResponseCode();
} catch (IOException e) {
System.out.println("Failed to connect to get response code");
e.printStackTrace();
}
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
System.out.println("Response message: " + con.getResponseMessage());
}
I solved the problem by using the HttpRequest external library. It gave me better control of the request and made for easier debugging of the problem. The server was receiving the request just fine, the problem was with the JSON encoding. Rather than putting the JSON object as a parameter in the request, I inserted it into the body of the http request and encoded it in UTF-8.
In the end, this is the code that worked:
String url = "https://api.parse.com/1/functions/sendEmailNow";
URL obj = new URL(url);
//Attempt to use HttpRequest to send post request to parse cloud
HttpRequest request = HttpRequest.post(obj).contentType("application/json");
request.header("X-Parse-Application-Id", "**************************");
request.header("X-Parse-REST-API-Key", "********************");
JSONObject jsonParam = new JSONObject();
jsonParam.put("emailId", emailId);
request.send(jsonParam.toString().getBytes("UTF8"));
if (request.ok())
System.out.println("HttpRequest WORKED");
else
System.out.println("HttpRequest FAILED " + request.code() + request.body());

Categories

Resources