I'm trying to make a POST request from my android app to a .php file but it doesn't work. It should send the scannedData value to my .php script but instead it returns "false: 500".
Does anybody know why? Since they changed that you can't use httppost anymore most of the answers on StackOverflow are outdated.
public class SendRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try{
//Enter script URL Here
URL url = new URL("https://example.com/code.php");
JSONObject postDataParams = new JSONObject();
//int i;
//for(i=1;i<=70;i++)
// String usn = Integer.toString(i);
//Passing scanned code as parameter
postDataParams.put("sdata",scannedData);
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
Related
I need to update existing parameters in the database.
My screen receives values in xml and it's those values that I want to update in the database using the method put.
Here's my put code that does not work correctly :
public class PatchClass extends AsyncTask<Void, String, String> {
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... String) {
StringBuilder result = new StringBuilder();
// Toast.makeText(LoginActivity.this,"No começo de doInbackground....",Toast.LENGTH_LONG).show();
// int id = 1;
try {
String urlLogin = "http://192.168.1.207/api/v2/bookdemo/_table/cad_users";
URL url = new URL(urlLogin);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
JSONObject postDataParams = new JSONObject();
conn.setRequestProperty("Content-type", "application/json");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("X-DreamFactory-Api-Key", "XXXXXXXXXXXXXXXX");
conn.setRequestProperty("X-DreamFactory-Session-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.XXXXXXXXXXXXXX.uVXdVTczx91z2NDGVV2quxvIEHhHUzX1hnVrNWQzoao");
conn.setRequestProperty("Authorization", "Basic dGhpYWdvLmNhbWFyZ29AZXZvbHV0aW9uaXQuY29tLmJyOmluaWNpYWwyMDE3'");
conn.setDoOutput(true);
conn.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
conn.getOutputStream());
out.write("resource");
conn.getInputStream();
conn.connect();
JSONObject resource = new JSONObject();
JSONArray array = new JSONArray();
array.put(postDataParams);
resource.put("resource", array);
postDataParams.put("id_user",id);
postDataParams.put("tx_name", nome);
postDataParams.put("tx_nickname", nickname);
postDataParams.put("password", password);
postDataParams.put("nu_cellphone", numcel);
postDataParams.put("tx_email", email);
Log.e("resource", postDataParams.toString());
System.out.println("After this Connection");
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
//writer.write(getPostDataString(postDataParams));
writer.write(resource.toString());
writer.flush();
writer.close();
os.close();
System.out.println("After this writers");
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
System.out.println("Funcionou!!");
Intent intent = new Intent(ActivityAttCad.this, MainActivity2.class);
startActivity(intent);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
I'm doing this program and I got this error:
Error:(93, 34) error: method getPostDataString in class MainActivity.DownloadTask cannot be applied to given types;
required: HashMap
found: String,int
reason: actual and formal argument lists differ in length
protected String doInBackground(Object... params) {
URL url;
String response = "";
try {
url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString("district", 1));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
With the following method:
private String getPostDataString(HashMap<String, Integer> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, Integer> entry:params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
}
return result.toString();
}
You should pass map as a parameter in getPostDataString method
protected String doInBackground(Object... params) {
URL url;
String response = "";
try {
url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
Map<String, Integer> inputMap = new HashMap<String, Integer>();
map.put("district", 1);
writer.write(getPostDataString(map);
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
You are passing a string and an integer while calling getPostDataString where as it expects a HashMap<String, Integer>. Java does not convert a string and integer to a map directly. You need to create a map in calling function and send it.
Replace the following statement
writer.write(getPostDataString("district", 1));
with
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("district",1);
writer.write(getPostDataString(m));
I'm working on an API and I am experiencing a strange thing. When I make an API request from which I receive a JSON response. In the browser I receive the following JSON:
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{
"Reason":"sfdfsdf",
"Date":"2016-10-02",
"SlotId":"1"
}
]
}]
But I receive a different JSON response on my Android device.
[
{
"SalesAgentPhone":"829698539",
"DriverStatus":"CustomerRescheduled",
"DriverStatusDescription":[
{"Reason":"sfdfsdf","Date":"2016-10-02","SlotId":"1"
}
]
}]
This is the class I'm using to make that Request
public class NewPost extends AsyncTask<String, Integer, String> {
private final Context context;
private final Registerinterface inter;
private int response_code = 0;
private HashMap<String, String> postDataParams;
private ProgressDialog prgDialog;
public NewPost(Context c, Registerinterface inter, HashMap<String, String> postParamater) {
context = c;
this.inter = inter;
this.postDataParams = postParamater;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (!new NetworkStatus(context).isNetworkAvailable()) {
inter.Result("", Constants.No_Internet);
this.cancel(true);
} else {
prgDialog = new ProgressDialog(new ContextThemeWrapper(context, android.R.style.Theme_DeviceDefault_Light_Dialog));
prgDialog.setMessage("Loading...");
prgDialog.show();
prgDialog.setIndeterminate(false);
}
}
#Override
protected String doInBackground(String... param) {
URL url;
String response = "";
try {
url = new URL(param[0]);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null)
sb.append(line + "\n");
response = sb.toString();
return response;
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prgDialog.dismiss();
if (result == null || result.equals("null"))
inter.Result("null", response_code);
else
inter.Result(result, response_code);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
I've been stuck on this problem for hours, any help would be appreciated.
You can remove the from your JSON data.
JSON.parse(data.replace(/"/g,'"'));
You might want to fix your JSON-writing script though, because " is not valid in a JSON object.
I need to send some variables to be stored into a database, and some to be displayed in the screen in a PHP page. I did not find how to do it all together and go to the webpage to show the variables on the screen with the POST method so I am trying to do it by passing them through the URL with the GET method.
POST method is working fine, and the variables are stored in the database, but after this, the app does not go to the webpage and shows another variable on the screen. Here is my code:
public class Main3Activity extends AppCompatActivity {
public String precio;
URL url;
Button b1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
b1 = (Button) findViewById(R.id.button_pago);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
new SendPostRequest().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void getMethod() throws IOException {
url = new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("https://www.webpage.com/login_app.php"); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("precio", "1€");
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("Success");
String line="";
getMethod();
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
Do somebody have an idea to solve it?
Thank you for your time.
EDIT:
Thanks to #user6749691, now I have got the following script to do the GET method:
private void openConnection(String method, URL url) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
public URL getMethod() throws IOException {
return new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
And then I call the function openConnection("GET", getMethod()); in the following lines of the 'SendPostRequest' class:
StringBuffer sb = new StringBuffer("Success");
String line="";
openConnection("GET", getMethod());
while((line = in.readLine()) != null) {
.
.
.
But I am getting Unhandled Exception in 'url.openConnection()' and in 'conn.setRequestMethod(method);'
First of all, try to use some great networking library as Retrofit or Volley.
Inside your getMethod you are just creating URL object. You need to open new URL connection.
Something like this:
private void openConnection(String method, URL url) {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
}
and then :
public URL getMethod() throws IOException {
return new URL("https://www.webpage.com/login_app.php?username=" + precio );
}
openConnection("GET", getMethod());
Try the following:
private String openConnection(String requestMethod, String link) {
URL url;
StringBuilder sb = new StringBuilder();
sb.append("");
try {
BufferedReader reader;
if(requestMethod == "GET"){
url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(requestMethod);
conn.setUseCaches(false);
conn.setDoInput(true);
conn.connect();
int STATUS = conn.getResponseCode();
Log.e(TAG, "ResponseCode: " + STATUS);
if(STATUS == 200 || STATUS == 201)
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
else
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
}
else {
url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
jsonSend.put("your_parameter", "parameter_value");
String output = jsonSend.toString();
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(output);
wr.flush();
reader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return sb.toString();
}
For the best practice, try to use the Retrofit
I'm trying to send POST request via HttpURLConnection, here is the code
public class BackgroundTask extends AsyncTask<String, Void, Void> {
Context context;
Activity activity;
StringBuffer str = null;
int responseCode;
String responseMessage;
public BackgroundTask(Context context) {
this.context = context;
this.activity = (Activity) context;
}
#Override
protected Void doInBackground(String... params) {
HttpURLConnection connection = null;
OutputStream outputStream = null;
InputStream inputStream = null;
BufferedReader reader = null;
BufferedWriter writer = null;
String method = params[1];
if(method.equals("post")) {
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
outputStream = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
writer.write(data);
responseCode = connection.getResponseCode();
responseMessage = connection.getResponseMessage();
inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
str = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
str.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else if(method.equals("get")) {
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void aVoid) {
TextView txt = (TextView) activity.findViewById(R.id.txt);
if(str != null)
txt.setText(str.toString());
Toast.makeText(activity, responseMessage, Toast.LENGTH_LONG).show();
}
}
responseCode is 200 which means everything went OK, however it says Undefined index: id
id is well defined inside php file
$user = User::find_by_id($_POST['id']);
echo json_encode($user);
and it works fine when I send post request from an html file yet when i send it from application it says id undefined which means that POST data is not sent.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask myTask = new BackgroundTask(MainActivity.this);
myTask.execute(link, "post", "id", "5");
}
});
this is how i instantiate asynctask object inside main activity
UPDATE: when i send not encoded string it works fine!
writer.write("id=5"); // works perfectly!
what is wrong with URLEncoder i use in the code?
I believe you have a problem in this line:
String data = URLEncoder.encode(params[2] + "=" + params[3], "UTF-8");
You are url-encoding the = as well as the params, that's why the server cannot recognise the form fields. Try to encode the params only:
String data = URLEncoder.encode(params[2], "UTF-8") + "=" + URLEncoder.encode(params[3], "UTF-8");
The reason is that URL encoding is for passing special characters like = in the value(or key). Basically, the server will split and parse the key-value pairs with & and = before doing the decoding. And when you url-encode the = character, the server simply couldn't recognise it during the split and parse phase.
When i need to communicate with the server i use this
Server Class
public static String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private static String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
OtherClass
//Run this inside an Asynctask
HashMap<String,String> data = new HashMap<>();
data.put("id", id);
String serverResponce = Server.sendPostRequest(URL,data);