JSON Post Request contains no parameters - java

I have a problem by my json post request. I created a JsonObject and want to post it to the server but the body of the post request which is received by the server contains nothing and I don't know why...
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
String contentType = "application/json";
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", "your name");
jsonObj.put("message", "your message");
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}

Provide "Content-Type" header to request with value "application/json". It seems server can't found proper message body mapper.

Related

send json to server(android)

Sorry for my english. I cant send json to server. I have error:
{"message":"Customer data is empty!","status":"error"}
Its my example, hov i must send json:
JSON example:
{
"company_id": "1",
"phones": [
"380000505050"
],
"photo": "/files/clients_photos/tmp/484629825.JPG",
"name": "sdfsdfdsf",
"birthdate": "10.02.2014",
"email": "sdf#sdf.ff",
"cars": {
"1": {
"car_brand_id": "9",
"car_model_id": "856",
"number": "AE5884AH",
"photo": "/files/clients_photos/tmp/484629824.JPG"
}
}
}
This is link, where i send json http://crm.pavlun.info/api/register
This is my code:
protected Void doInBackground(String... params) {
JSONParser operationLink = new JSONParser();
ArrayList<NameValuePair> postInform = new ArrayList<NameValuePair>();
postInform.add(new BasicNameValuePair("company_id", "2"));
postInform.add(new BasicNameValuePair("phones", "380950466589"));
postInform.add(new BasicNameValuePair("name", "Alexy"));
postInform.add(new BasicNameValuePair("birthdate", "12.03.2014"));
postInform.add(new BasicNameValuePair("email", "nesalexy#mail.ru"));
postInform.add(new BasicNameValuePair("photo", "/files/clients_photos/tmp/484629825.JPG"));
JSONObject registration = null;
try {
Log.e("perform link", postInform.toString()); //its output [company_id=2, phones=380950466589, name=Alexy, birthdate=12.03.2014, email=nesalexy#mail.ru, photo=/files/clients_photos/tmp/484629825.JPG]
registration = operationLink.makeHttpRequest(registrationURL, "POST", postInform);
Log.e("Link", registration.toString()); //its output {"message":"Customer data is empty!","status":"error"}
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
This is JSONparser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) throws JSONException {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
//return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
}
}
I believe I had the same problem previously, strangely enough, servers differ in the way they accept post data.
here is an example
the following method works for a jetty server but not Play:
public static void sendPost(String data,String url) throws Exception{
org.apache.http.impl.client.DefaultHttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
org.apache.http.client.methods.HttpPost post = new org.apache.http.client.methods.HttpPost(url);
org.apache.http.entity.StringEntity entity = new org.apache.http.entity.StringEntity(data.toString());
post.setEntity(entity);
client.execute(post);
}
the followig method works for Play server but not jetty:
public static void sendPostV2(String data, String url) throws Exception{
org.apache.commons.httpclient.HttpClient client =
new org.apache.commons.httpclient.HttpClient();
org.apache.commons.httpclient.methods.PostMethod method =
new org.apache.commons.httpclient.methods.PostMethod(url);
method.addParameter("data", data);
client.executeMethod(method);
method.releaseConnection();
}
we still haven't figured out why, but oh well whatever works baby.
in your case please feel free to use any of the following method (note download the required apache packages). hopefully one of them works for you.

Save zip file android

NODE.js : (zip the file)
app.post('/api/db', function(req, res){
if(req.body.type == 'Control'){
var zip = new AdmZip();
console.log(req.body.type);
zip.addLocalFolder(__dirname +'/XXX/Temp/1');
var willSendthis = zip.toBuffer();
zip.writeZip(__dirname +'/files.zip');
res.sendFile(zip);
}
});
JAVA : (send a request to want to zip file)
public class HttpAsyncTask extends AsyncTask<String, Void, String> {
public ArrayList<String> aList= new ArrayList<String>();
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type", "Control"));
JSONObject json = jsonParser.makeHttpRequest(url, type, params);
Log.d("Create Response", json.toString());
return null;
}
protected void onPostExecute(String result) {
}
}
JSON PARSER:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "PUT"){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(url);
httpPut.setEntity(new UrlEncodedFormEntity(params));
for (NameValuePair nvp : params){
Log.d("parameter", nvp.getName());
Log.d("parameter", nvp.getValue());
}
HttpResponse httpResponse = httpClient.execute(httpPut);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "DELETE"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String param = null;
for (NameValuePair nvp : params){
param = nvp.getValue();
url += "/" + param;
Log.d("url = ", url);
}
url = url.trim();
Log.d("url = ", URLEncoder.encode(url, "UTF-8"));
HttpDelete httpDelete = new HttpDelete(url);
HttpResponse httpResponse = httpClient.execute(httpDelete);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-9"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I sent .zip file from server to android devices. I want to save into the android devices memory.
How can i save .zip file which is sended by node.js server?

How to send a Json to a web service using HttpPost

Hi I want to send a json object to a web service , I have tried almost everything without success. When the webservice recives the data it returns "eureka" , so I want to be able to see the response too.
public void sendData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://pruebaproyectosmi.azurewebsites.net/home/Insert?data=");
try {
httppost.setEntity(new UrlEncodedFormEntity(json));
// 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
}
}
private void SendBookingData(final String SendCustomerId,final String SendCustomerName, final String BookingDate,
final String BookingTime, final String SendNetAmount,final String SendTotalAmount, final String SendTotalQuantity,
final String SendDeliveryDate, final String GetBranchId,final String Senduserid,final String Sendratelistid) {
HttpClient client = new DefaultHttpClient();
JSONObject json = new JSONObject();
try {
String SendBookingURL= "your url";
HttpPost post = new HttpPost(SendBookingURL);
HttpResponse response;
json.put("GetcustomerName", SendCustomerName);
json.put("GetBookingDate",BookingDate);
json.put("GetTotalCost", SendTotalAmount);
json.put("GetNetAmount", SendNetAmount);
json.put("GetTotalQuantity",SendTotalQuantity );
json.put("GetCustomerId", SendCustomerId);
json.put("GetDeliveryDate", SendDeliveryDate);
json.put("GetBookingtime", BookingTime);
json.put("GetBranchId", GetBranchId);
json.put("GetUserId", Senduserid);
json.put("GetRateListId", Sendratelistid);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
try {
response = client.execute(post);
HttpEntity entity = response.getEntity();
if(entity != null) {
ResponseSummaryTable = EntityUtils.toString(entity);
System.out.println("body" + ResponseSummaryTable);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
catch(Exception e){
e.printStackTrace();
}
}
Send string entity instead
CODE:
HttpClient client = new DefaultHttpClient();
HttpUriRequest request;
request = new HttpPost(<-URL->);
StringEntity entity = new StringEntity(<-Your JSON string->);
((HttpPost) request).setEntity(entity);
((HttpPost) request).setHeader("Content-Type",
"application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
This code will send json as string entity to server and receives HttpEntity as response

App crashes on httGet when attempting to send to Json?

My app crashes on "((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),"UTF-8"));" and throws an exception "java.lang.ClassCastException:org.apache.http.client.methods.HttpGet".
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(uri);
// Prepare JSON to send by setting the entity
((HttpResponse) httpGet).setEntity(new StringEntity(jo.toString(),
"UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
response = httpClient.execute(httpGet);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;
Activity{
oncreate{
new HitService().execute(addparams here);
}
}
protected String doInBackground(String... params) {
String result = null;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://your url=" + params[0]);
HttpResponse response;
try {
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
If you want to put some data to request body, you have to use HttpPost instead of HttpGet. HttpPost has function for this: setEntity(HttpEntity entity)
Example:
JSONObject jo = new JSONObject();
try {
jo.put("devicetoken", devicetoken);
URI uri = new URI("http", "praylistws-dev.elasticbeanstalk.com",
"/rest/list/myprayerlist/"+Helper.email, null, null);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
// Prepare JSON to send by setting the entity
httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
httpGet.setHeader("Accept-Encoding", "application/json");
httpGet.setHeader("Accept-Language", "en-US");
// Execute POST
HttpResponse response = httpClient.execute(httpPost);
String string_response = EntityUtils.toString(response.getEntity());
string_resp = string_response += "";
} catch (Exception ex) {
ex.printStackTrace();
}
save(string_resp);
return result;

Java HTTP-Request with POST-Data

I wrote the following code in java to send some data via POST-Variables to a PHP-File of my website and then I want to get the source code of this website.
public DatabaseRequest(String url, IDatabaseCallback db_cb)
{
this.db_cb = db_cb;
site_url = url;
client = new DefaultHttpClient();
request = new HttpPost(site_url);
responseHandler = new BasicResponseHandler();
nameValuePairs = new ArrayList<NameValuePair>(0);
}
public void addParameter(List<NameValuePair> newNameValuePairs)
{
nameValuePairs = newNameValuePairs;
}
public void run()
{
db_cb.databaseFinish(getContent());
}
public String[] getContent()
{
String result = "";
try {
request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
result = client.execute(request, responseHandler);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] result_arr = result.trim().split("<br>");
for (int i = 0; i < result_arr.length; i++)
{
result_arr[i] = result_arr[i].trim();
}
return result_arr;
}
When I want to run this code, then eclipse throws the following error message:
Try this:
// executes the request and gets the response.
HttpResponse response = client.execute(httpPostRequest);
// get the status code--- 200 = Http.OK
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity httpEntity = response.getEntity();
responseBody = httpEntity.getContent();
if (statusCode = 200) {
// process the responseBody.
}
else{
// there is some error in responsebody
}
EDIT: To handle UnsupportedEncodingException
Before making HTTP request you need to encode the post data in order to convert all string data into valid url format.
// Url Encoding the POST parameters
try {
httpPostRequest.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
// writing error to Log
e.printStackTrace();
}

Categories

Resources