Http post how to add parameter to my URL - java

I want to add my Fbid to php DB , how can I do this?
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... data) {
String result = null;
try {
// 1. create HttpClient
URL url = new URL(data[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fbid", fbid));
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
connection.connect();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
My compileSdkVersion is 24 and buildToolsVersion "24.0.1".
Why I cant add to the db? Is that because NameValuePair is deprecated?

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

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

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

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 do i enable httpclient in android studios?

Help! How do i enable the following httpclient in my android studios? Can't seem to find NameValuePair, BasicNameValuePair, Httpclient, Httppost and apparently my HTTPConnectionParams are depracated? How do i resolve them?
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name",user.name));
dataToSend.add(new BasicNameValuePair("email",user.email));
dataToSend.add(new BasicNameValuePair("password",user.password));
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");
try{
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
}catch (Exception e) {
e.printStackTrace();
}
I assume you may be using sdk 23+, try to use URLConnection or downgrade to sdk 22.
I recently had to change almost all of my code because that library has been deprecated. I believe we have been advised to use the original Java net library from now on.
Try the following
try{
URL url = new URL(SERVER_ADDRESS + "Register.php");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
String postData = URLEncoder.encode("name","UTF-8")
+"="+URLEncoder.encode(user.name,"UTF-8");
postData += "&"+URLEncoder.encode("email","UTF-8")
+"="+URLEncoder.encode(user.email,"UTF-8");
postData += "&"+URLEncoder.encode("password","UTF-8")
+"="+URLEncoder.encode(user.password,"UTF-8");
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(connection.getOutputStream());
outputStreamWriter.write(postData);
outputStreamWriter.flush();
outputStreamWriter.close();
}catch(IOException e){
e.printStackTrace();
}
Hope it helps
BasicNameValuePair is also deprecated. Use HashMap to send keys and values.
HashMap documentation: http://developer.android.com/reference/java/util/HashMap.html
Use this method in order to post data to the "yourFiles.php".
public String performPostCall(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) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
throw new HttpException(responseCode+"");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(Map<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();
}
You can also use the Volley Library from google to get your job done.
Example of using the library:
RequestQueue queue = Volley.newRequestQueue(activity);
StringRequest strRequest = new StringRequest(Request.Method.POST, "Your URL",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("Home_Fragment", "Error: " + response);
Toast.makeText(activity, "Success", Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(getApplicationContext(), "Error: " + error.getMessage());
Toast.makeText(activity, error.toString(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", user.name);
params.put("email", user.email;
params.put("password", user.password);
return params;
}
};
queue.add(strRequest);
);

Categories

Resources