i want to send some data to server on a specific url in json format but is not working. my json format is
JSON Object﹕ {"appt_email":"grddgf#ffgh.com","appt_service":"Test services 11","appt_contact":"8554688564","appt_time":"18.44","appt_name":"fddvnhff","appt_date":"18\/9\/2015"}
i am using Chrome Poster extension to test it. when i use it the data is sent properly. bt when i send from application it is not working.
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(
"http://tipseducation.com/system/eadmin/insertschedule/");
httpRequest.setHeader("Content-Type", "application/json");
JSONObject json = new JSONObject();
//StringEntity se = new StringEntity(json.toString()); httpRequest.setEntity(se); httpRequest.setHeader("Accept", "application/json");
StringEntity se = new StringEntity(json.toString());
se.setContentEncoding("UTF-8");
se.setContentType("application/json");
json.put("appt_name", ed_name);
json.put("appt_email", ed_email);
json.put("appt_contact", ed_contact);
json.put("appt_date", ed_date);
json.put("appt_time", ed_time);
json.put("appt_service", ed_spinner);
}
I would use String Request.
StringRequest sr = new StringRequest(type, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};
Related
I am trying to call a https post api from android app. It is giving 403 permission denied error. But the api works fine when called from postman or CURL in windows cmd.
In android i have tried Volley and OkHttpClient but the response from both is same.I am attaching codes for both libraries. Any help regarding this will be appreciated. Thanks in advance.
Volley
RequestQueue queue = Volley.newRequestQueue(getActivity());
String url = "https://xxxxx.com/api.php";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response.
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put("content1", "xyz");
MyData.put("content2", "xyz");
return MyData;
}
}; queue.add(MyStringRequest);
OkHttpClient
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("content1", "xyz")
.add("content1", "xyz")
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url)
.post(formBody)
.build();
try {
okhttp3.Response response = client.newCall(request).execute();
// Do something with the response.
} catch (IOException e) {
e.printStackTrace();
}
make sure oyu have the correct content type in the header. for instance in Volley
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-type", "application/x-www-form-urlencoded");
return params;
}
I am developing an Android App
The below mentioned is the link .
"http://example.com.in/ai/abc?var="+var
where var is a variable where result has come.I want to post the data available in the var along with the link . I am new to android so I want to know How to do POST method in Android App.
You should do something like this:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
You can use Android Volley Library to post your data to your php script.Here is the example of Volley Request
//Declare the URL you want to send
public static String YOUR_URL = "http://example.com.in/ai/abc?var=";
private void postDataToServer() {
//volley request
//here you can choose your method,GET/POST,in this case is Post
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.POST,
YOUR_URL , null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//if send data success do something here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//if having error to make request to server do something here
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//send your parameter here
Map<String, String> parameters = new HashMap<>();
parameters.put("yourVariable", "var");
return parameters;
}
//adding header to authenticate
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
return headers;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonReq);
}
You can look at this tutorial to see how to post data from Android and get the data in your php script.
i use this code for post a request to instagram and get accesstoken.
URL url = new URL(tokenURLString);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("POST");
httpsURLConnection.setDoInput(true);
httpsURLConnection.setDoOutput(true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream());
outputStreamWriter.write("client_id="+CI +
"&client_secret="+ CS +
"&grant_type=authorization_code" +
"&redirect_uri="+CALLBACK_URL+
"&code=" + requestToken);
outputStreamWriter.flush();
JSONObject jsonObject = new JSONObject(StreamToString.get(httpsURLConnection.getInputStream()));
how can i do this with android volley ?
Ive just actually implemented this myself. This is the code i used.
public void requestAccessToken(final String code) {
StringRequest request = new StringRequest(Request.Method.POST, TOKENURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("Success Response = ", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error Response = ", error.toString());
}
}) {
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", CLIENTID);
params.put("client_secret", CLIENTSECRET);
params.put("grant_type", "authorization_code");
params.put("redirect_uri", REDIRECTURL);
params.put("code", code);
return params;
}
};
Volley.newRequestQueue(this).add(request);
}
Try checking out this tutorial:
Asynchronous HTTP Requests in Android Using Volley
I used this in the first time I applied volley on a project. Volley is pretty straightforward to use.
I use a HttpPost in my code, where I add the entity like this:
String bodyContent = ".......";
HttpPost httpost = new HttpPost(url);
StringEntity se = new StringEntity(bodyContent);
httpost.setEntity(se);
Now I want to change HttpPost in the Volley Request.
How to set setEntity?
I do not understand how I can insert my string bodyContent.
Should I use another method?
boolean contentType = true/false;
//new post request in to volley
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Error.Response", "OK");
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", "KO");
}
}
) {
//add body content-type
#Override
public String getBodyContentType() {
if (contentType) {
return "application/json; charset=utf-8";
} else {
return "text/plain; charset=utf-8";
}
}
//add header
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> params = new HashMap<String, String>();
params.put("VLHASH", "464646");
return params;
}
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("name", "Alif");
params.put("domain", "http://itsalif.info");
return params;
}
};
queue.add(postRequest);
You just need to override getBody() as well like you have overridden getBodyContentType in your StringRequest
Sample Code
String body = "test body";
#Override
public byte[] getBody() throws AuthFailureError {
return body.getBytes();
}
This is the first time I'm working with JSON but I'm experimenting with POST requests.
I want to make a POST request to this website http://jsonblob.com/api
My code works when I use an asynctask + httppost
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new PostJsonTask().execute();
}
private class PostJsonTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
HttpResponse response = post();
Header s = response.getFirstHeader("Location");
Log.d("PostJsonTask", s.getValue());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private HttpResponse post() throws Exception {
// convert parameters into JSON object
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
JSONObject holder = new JSONObject(params);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity se = new StringEntity(holder.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
post.setEntity(se);
return client.execute(post);
}
}
With this code I can succesfully get the Location parameter.
But I want to do this with the Volley library, I already have the following code :
private static final String url = "http://jsonblob.com/api/jsonBlob";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
headers.put("Content-type", "application/json");
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Robby");
params.put("pass", "zqdqzdqdqzd");
return params;
}
#Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
Map<String, String> headers = response.headers;
String location = headers.get("Location");
Log.d("PostJsonTask", location);
return super.parseNetworkResponse(response);
}
};
queue.add(request);
}
private ErrorListener createErrorListener() {
return new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
};
}
private Listener<String> createResponseListener() {
return new Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("PostJsonTask", response);
}
};
}
But this returns a VolleyError with code 400. How can I fix this?
Instead of trying to set Content-type of header try to set for bodyContentType and in postman(web) also you are setting the content type of body only
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, obj,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
})
#Override
public String getBodyContentType() {
return "application/json";
}
};
Don't use the getParams override.
Instead, create a JSON with these parameter and provide as the body of the request like they do in JsonObjectRequest (or just use a JsonObjectRequest instead of a StringRequest), e.g.
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("user", "Robby");
jsonObject.put("pass", "zqdqzdqdqzd");
} catch (JSONException e) {
// handle exception (not supposed to happen)
}
StringRequest request = new StringRequest(Request.Method.POST, url, createResponseListener(), createErrorListener()) {
// your code without getParams
#Override
public byte[] getBody() {
try {
return jsonObject.toString.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
// not supposed to happen
return null;
}
}
}