How to do an update or "PUT" via json on android? - java

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

Related

Post request on Android to .php file

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

method in class cannot be applied to given types; required: HashMap<String,Integer>

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

Supporting Sessions Without Cookies in Tomcat #duplicate

I have an Web Application with Spring Security Framework and running on Tomcat 8. Now, I am facing a new problem to create android app which support user sessions without cookies. I tried to find some documentation like this and i tried it with using HttpUrlConnection ( I don't know which one is more better with other ), this is my failure code.
public static String jsessionid = SessionIdentifierGenerator.nextSessionId();
public static String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
Log.d("url = ",requestURL);
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(45000);
conn.setConnectTimeout(45000);
conn.setRequestMethod("POST");
Log.d("Cookie : ", jsessionid);
conn.setRequestProperty("Cookie","JSESSIONID=" + SessionIdentifierGenerator.nextSessionId());
conn.setDoInput(true);
conn.setDoOutput(true);
// conn.connect();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
int responseCode=conn.getResponseCode();
writer.close();
os.close();
System.out.println(".toString() = "+responseCode);
System.out.println(".HttpsURLConnection.HTTP_OK = "+HttpsURLConnection.HTTP_OK);
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;
}
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()){
Log.d("entry.getKey() = ",entry.getKey());
Log.d("entry.getValue() = ",entry.getValue());
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"));
}
System.out.println("tetstes = "+result.toString());
return result.toString();
}
this methode for create a new session.
public final class SessionIdentifierGenerator {
private static SecureRandom random = new SecureRandom();
public static String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
HashMap<String, String> parameter = new HashMap<String, String>();
parameter.put("username", username);
parameter.put("password", password);
and the last i call this performPostCall("http://localhost:8080/login/authenticate?spring-security-redirect=/login/ajaxSuccess", parameter);

Android GET inside a POST not working

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

How to stream a JSON object to a HttpURLConnection POST request

I can not see what is wrong with this code:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
On the server, I am getting no post content at all, a zero length string.
Try
...
httpCon.setRequestMethod("POST");
httpCon.connect(); // Note the connect() here
...
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
...
osw.write(msg.toString());
osw.flush();
osw.close();
to send data.
to retrieve data try:
BufferedReader br = new BufferedReader(new InputStreamReader( httpCon.getInputStream(),"utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(""+sb.toString());
public String sendHTTPData(String urlpath, JSONObject json) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(json.toString());
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}`
call this methopd in doitbackground in asynctask
HttpURLConnection is cumbersome to use. With DavidWebb, a tiny wrapper around HttpURLConnection, you can write it like this:
JSONObject msg; //passed in as a parameter to this method
Webb webb = Webb.create();
JSONObject result = webb.post("http://my-url/path/to/res")
.useCaches(false)
.body(msg)
.ensureSuccess()
.asJsonObject()
.getBody();
If you don't like it, there is a list of alternative libraries on the link provided.
Why should we all write the same boilerplate code every day? BTW the code above is more readable and less error-prone. HttpURLConnection has an awful interface. This has to be wrapped!
Follow this example:
public static PricesResponse getResponse(EventRequestRaw request) {
// String urlParameters = "param1=a&param2=b&param3=c";
String urlParameters = Piping.serialize(request);
HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);
PricesResponse response = null;
try {
// POST
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
// RESPONSE
BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
String json = Buffering.getString(reader);
response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);
writer.close();
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
conn.disconnect();
System.out.println("PricesClient: " + response.toString());
return response;
}
public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {
return RestClient.getConnection(endPoint, "POST", urlParameters);
}
public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {
System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
HttpURLConnection conn = null;
try {
URL url = new URL(endPoint);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/plain");
} catch (IOException e) {
e.printStackTrace();
}
return conn;
}
this without json String post data to server
class PostLogin extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
String response = null;
Uri.Builder builder= new Uri.Builder().appendQueryParameter("username","amit").appendQueryParameter("password", "amit");
String parm=builder.build().getEncodedQuery();
try
{
response = postData("your url here/",parm);
}catch (Exception e)
{
e.printStackTrace();
}
Log.d("test", "response string is:" + response);
return response;
}
}
private String postData(String path, String param)throws IOException {
StringBuffer response = null;
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
OutputStream out = connection.getOutputStream();
out.write(param.getBytes());
out.flush();
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
response = new StringBuffer();
while ((line = br.readLine()) != null) {
response.append(line);
}
br.close();
}
return response.toString();
}

Categories

Resources