I am having trouble posting a JSONArray of values to my WCF Service. When I post the data from Fiddler or .Net Test Client it works fine. Every time I try to post from my android application I get Request Error
This is the JSON data that I send to my WCF Service from the android application. I've tried this exact data from Fiddler and it works
[{"date":"2013-02-22 15:30:374:021","id":"1","description":"test","name":"test"},
"date":"2013-02-25 11:56:926:020","id":"2","description":"ghy","name":"fhh"},
"date":"2013-02-25 11:56:248:026","id":"3","description":"ghfm","name":"run"}]
My android code
public JSONObject makeHttpPost(String url, String method, JSONArray params) {
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type",
"application/json; charset=utf-8");
StringEntity se = new StringEntity(params.toString(),"UTF-8");
se.setContentType("application/json;charset=UTF-8");
httpPost.setEntity(se);
Log.e("Gerhard", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My WCF Service
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "updateOrderAddress")]
String UpdateOrderAddress(Stream JSONdataStream);
public String UpdateOrderAddress(Stream JSONdataStream)
{
try
{
// Read in our Stream into a string...
StreamReader reader = new StreamReader(JSONdataStream);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsOrder" record.
if (JSONdata == null)
{
// Error: Couldn't deserialize our JSON string into a "wsOrder" object.
return "null";
}
return JSONdata; // Success !
}
catch (Exception e)
{
return e.ToString();
}
}
The error I'm getting
02-26 14:00:56.185: E/Gerhard(31064): <p>The server encountered an error processing the request. The exception message is 'Incoming message for operation 'UpdateOrderAddress' (contract 'IService1' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Json'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details. The exception stack trace is: </p>
I have called multiple GET requests from android application to same WCF Service and it works great, but now I need to send an array of data to the wcf service. Please please help me.Thanks in advance
remove
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json; charset=utf-8");
from ur code
Related
I would like to send an http request to custom api.
I have the request details, and it is working using postman(http client).
Im trying to translate that request to android, using AsyncTask.
I couldnt managed to understand few things:
first, how to send the Bearer token that I have(oauth 2.0).
the second, how to send a jason body.
all the details about the request are in the following link:
https://web.postman.co/collections/7428863-ca5b907d-2752-4d4e-b8a8-29d5cd0dc098?version=latest&workspace=03f5fe5b-0ecd-43f8-8759-3aa868f4cb7f
my "DoInBackground" :
protected Void doInBackground(Void... voids) {
response = null;
Log.v("DoInBackground","entered");
//sending Data
if (valid) {
Log.v("ifvaild","entered");
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("https://dmyzcsu4e68qfgi56y7l2qu5ky40da2o.ui.nabu.casa/api/services/script/turn_on");
//httpPost.addHeader("Accept-Language", "he");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
nameValuePair.add(new BasicNameValuePair("Authorization", "Bearer My Bearer"));
nameValuePair.add(new BasicNameValuePair("Content-Type", "application/json"));
nameValuePair.add(new BasicNameValuePair("script.turn_on", "script.gt1"));
Log.v("nameValue","entered");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, HTTP.UTF_8));
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
Log.v("HttpClient","entered");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
this is not working, I get an authentication failure from the server
thanks for your help!
You need to add those pairs in the header. And add the body as entity.
// headers
httpPost.addHeader("Authorization", "Bearer My Bearer");
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("script.turn_on", "script.gt1");
// body
String bodyString = "{\"data\":1}"; // your json string
StringEntity bodyEntity = new StringEntity(bodyString);
httpPost.setEntity(bodyEntity);
Just a tip. Look into Retrofit2 library to do all of this.
Android HTTP PUT not sending JSON request to server resulting in HTTP 405 Method not allowed.
Below is my async task background code
HttpClient httpclient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut("URL");
String jsonresponse = "";
try {
StringEntity se = new StringEntity(gson.toJson(resultPojo).toString());
se.setContentType("application/json;charset=UTF-8");//text/plain;charset=UTF-8
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httpPut.setEntity(se);
httpPut.setHeader("Accept", "application/json");
httpPut.setHeader("Content-type", "application/json");
HttpResponse response = httpclient.execute(httpPut);
HttpEntity httpEntity = response.getEntity();
jsonresponse = EntityUtils.toString(httpEntity);
System.out.println("res .... "+jsonresponse);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
serverside code :
#POST
#Path("{id}")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public Response submitUserResponse(#PathParam("userId") int userId,
#PathParam("id") int id, List<ResultPojo> responses) {
try {
//core logic goes here
return Response.status(Response.Status.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
Alright just like what was discussed it is most likely a mismatch different HTTP methods, in this case A Put and a post, whenever you ever encounter that HTTP code(405) do perform a validation on the methods you used, it happens.405 errors often arise with the POST method. You may be trying to introduce some kind of input form on the Web site, but not all ISPs allow the POST method necessary to process the form.A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.
i am calling webservice in this way..
public static String POST(String url, ArrayList<ModelLatLog> list,Context con){
InputStream inputStream = null;
String result = "";
AppLog.logString(TAG+"URL : "+url);
AppLog.logString(TAG+"ListSize: "+list.size());
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "[";
for(int j=0;j<list.size();j++){
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("DId", ""+list.get(j).get_idDevice());
jsonObject.accumulate("Lat", ""+list.get(j).getLat());
jsonObject.accumulate("Long", ""+list.get(j).getLong());
jsonObject.accumulate("DIn", ""+list.get(j).getDt());
jsonObject.accumulate("TIn", ""+list.get(j).getTm());
jsonObject.accumulate("Dce", ""+list.get(j).getDce());
if(j==0 ){
json = json+""+jsonObject.toString();
AppLog.logString(TAG+"if j: "+j);
}
else{
json = json+","+jsonObject.toString();
AppLog.logString(TAG+"else j: "+j);
}
}
json = json+"]";
AppLog.logString(TAG+"JSON: "+json);
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
int resopnceStatus = httpResponse.getStatusLine().getStatusCode();
AppLog.logString(TAG+"set data resopnceStatus: "+resopnceStatus);
inputStream = httpResponse.getEntity().getContent();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
e.printStackTrace();
AppLog.logString("InputStream"+ e.getLocalizedMessage());
}
return result;
}
AppLog is nothing it's log.d
it's giving me error like
11-19 18:15:39.088: I/Service(32261): Utility: set data resopnceStatus: 500
11-19 18:15:39.096: I/Service(32261): result: <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="en">Server was unable to process request. ---> Data at the root level is invalid. Line 1, position 1.</soap:Text></soap:Reason><soap:Detail /></soap:Fault></soap:Body></soap:Envelope>
Looks like the webservice is returning you an error, so the HTTP POST call actually worked.
Are you sending it the correct format? looks like its expecting XML request and you send JSON.
Why you are Taking so burden...
Just use volley service...It will take care of every thing...
Just use StringRequest in Volley..your task will be easy...
Download volley example here
If you haven't already figure out your problem, I believe ksoap2 is more intuitive for dealing with webservices on android, this link has a good example on it.
is there clear Example of Android ksoap2 returning array of objects from .Net Web service?
I am trying to post two json encoded values to my webservice using the below code. but i am not getting any response (Just Blank Output and No errors on LogCat). However, I have tried posting the same parameters from PHP to my webservice using cURL which works great.
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
try {
json.put("name","email");
json.put("email", "email");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept-Encoding", "application/json");
post.setHeader("Accept-Language", "en-US");
List<NameValuePair> ad = new ArrayList<NameValuePair>(2);
ad.add(new BasicNameValuePair("json", json.toString()));
post.setEntity(new UrlEncodedFormEntity(ad));
Log.i("main", "TestPOST - nVP = "+ad.toString());
response = client.execute(post);
if(response!=null) {
HttpEntity entity = response.getEntity();
output = EntityUtils.toString(entity,HTTP.UTF_8); //Get the data in the entity
}
} catch(Exception e) {
}
Try Getting your response by this
if (response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
}
You're catching Exception (the super class) without logging. If an exception of any kind occurs in your try block the code will jump to the catch without any log.
Change this:
catch(Exception e){
}
with
catch (Exception e)
Log.e("myappname", "exception", e);
}
If there is no response, you should definitely check your catch exception e, since you didn't write anything in the clause, there might be something happening but you didn't notice.
So I am trying to post to a rails app from an Android app I am writing. I am able to post successful from inside the rails app. I was also able to post successfully using a chrome add on called Simple Rest client.
When I try and post from the Android app its hitting the rails app but creating an empty post. None of the input data is being received by rails.
I read that 3rd party applications are only able to GET from a Rails app depending on authentication so to make sure this wasn't the issue I was having I added this to my Rails config.
# de-activate tolken auth
config.action_controller.allow_forgery_protection = false
At this point I am unsure as to where my issue lies, with my Rails backend or my Android client.
ok so the Rails post method in my controller that I'm trying to reach is here
# POST /orders
# POST /orders.json
def create
#order = Order.new(params[:order])
respond_to do |format|
if #order.save
format.html { redirect_to #order, notice: 'Order was successfully created.' }
format.json { render json: #order, status: :created, location: #order }
else
format.html { render action: "new" }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
Here is the Android java code for sending the Post Request.
This is the method passing in the User input data I am trying to POST
private void postInformationtoAPI() {
showToast("POSTING ORDER");
List<NameValuePair> apiParams = new ArrayList<NameValuePair>();
apiParams.add(new BasicNameValuePair("drinks_id", GlobalDrinkSelected));
apiParams.add(new BasicNameValuePair("name", GlobalEditTextInputName));
apiParams.add(new BasicNameValuePair("paid" , GlobalIsPaid));
bgtPost = new BackGroundTaskPost(MAP_API_URL_POST_ORDER, "POST", apiParams);
bgtPost.execute();
goToOrderCompleted();
}
And this is the class that it is passed to, permorming the HTTP POST.
public class BackGroundTaskPost extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
String URL = null;
String method = null;
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public BackGroundTaskPost(String url, String method, List<NameValuePair> params) {
this.URL = url;
this.postparams = params;
this.method = method;
for (int i = 0; i < postparams.size(); i++){
String test = postparams.get(i).toString();
Log.d("This is in the lisht:", test);
}
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8));
Log.i("postparams : ", postparams.toString());
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
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(postparams, "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 {
Log.i("Logging out *is* before beffered reader", is.toString());
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
Log.i("Logging out *is* after beffered reader", is.toString());
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("json: ",json);
} 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 TEST " + e.toString());
}
// return JSON String
return jObj;
}
}
This is the what log's out for postparams in the above class, so I know data is actually being sent
04-03 21:36:23.994: I/postparams :(690): [drinks_id=41, name=Dave, paid=True]
This is what Log Cat is showing as a response from the server
04-03 20:56:08.247: I/json:(690): {"created_at":"2013-04-03T20:56:06Z","drinks_id":null,"id":1351,"name":null,"paid":null,"served":null,"updated_at":"2013-04-03T20:56:06Z"}
I am really struggling to understand where the issue lies with this and have been stuck on it for quite awhile. Any insight would be much appreciated. And if any more information is needed just shout.
Edit: logs from server
This is a successful post from the simple REST client
2013-04-03T23:13:31+00:00 app[web.1]: Completed 200 OK in 15ms (Views: 8.7ms | ActiveRecord: 5.2ms)
2013-04-03T23:13:42+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 23:13:42 +0000
2013-04-03T23:13:42+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T23:13:42+00:00 app[web.1]: Parameters: {"updated_at"=>nil, "drinks_id"=>51, "id"=>1021, "name"=>"Test", "paid"=>true, "served"=>nil, "created_at"=>nil, "order"=>{"drinks_id"=>51, "name"=>"Test", "paid"=>true, "served"=>nil}}
2013-04-03T23:13:43+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=1ms service=25ms status=201 bytes=138
2013-04-03T23:13:43+00:00 app[web.1]: Completed 201 Created in 15ms (Views: 0.6ms | ActiveRecord: 13.2ms)
This is from the android app posting
2013-04-03T22:56:45+00:00 app[web.1]: Started POST "/orders.json" for 89.101.112.167 at 2013-04-03 22:56:45 +0000
2013-04-03T22:56:45+00:00 app[web.1]: Processing by OrdersController#create as JSON
2013-04-03T22:56:45+00:00 app[web.1]: Completed 201 Created in 23ms (Views: 2.2ms | ActiveRecord: 16.3ms)
2013-04-03T22:56:45+00:00 heroku[router]: at=info method=POST path=/orders.json host=fyp-coffeeshop.herokuapp.com fwd="89.101.112.167" dyno=web.1 connect=4ms service=37ms status=201 bytes=138
You're setting a content-type of JSON but not actually sending JSON, you're sending standard POST url-encoded parameters.
You need to actually send a JSON object:
JSONObject params = new JSONObject();
params.put("drinks_id", GlobalDrinkSelected);
params.put("name", GlobalEditTextInputName);
params.put("paid", GlobalIsPaid);
StringEntity entity = new StringEntity(params.toString());
httpPost.setEntity(entity);
The problem is that when you're building the POST in Android you're over-writing the entity (the body). You initially set it and then you set it again, effectively clearing out what you already set.
This is correct:
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
But then a couple of lines later you over-write it with:
httpPost.setEntity(new StringEntity("UTF-8"));
So ditch that 2nd setEntity() call.
You can achieve what you're trying to do - setting the POST body in UTF-8 by tweaking your code like:
httpPost.setEntity(new UrlEncodedFormEntity(postparams, HTTP.UTF_8));