Android calling webservice issue - android

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?

Related

How to POST list of objects as JSON from Android client to PHP REST API?

Scenario:
REST API: PHP Slim Framework
Android HTTP client library: loopj
I am storing an ITEM as json string in sqlite.
I want to POST this JSON on server. Each item is a record in my SQLite database.
What I am currently doing?
I have JSON with list of objects. I want to POST it to my PHP based REST API.
Here is the code
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Item item = new Item();
try {
item.setOfflineId(Long.parseLong(cursor.getString(0)));
item.setName(cursor.getString(1));
item.setImageLocalPath(itemPayload.getImageLocalPath());
item.setToUpdate(Boolean.parseBoolean(cursor.getString(3).toString()));
item.setDeviceID(cursor.getString(4));
item.setCreatedDate(cursor.getString(5));
//item.setImageBlob(cursor.getBlob(5));
String imageURL = itemPayload.getImageLocalPath();
File imageFile = new File(imageURL);
} catch (Exception e) {
Log.d("Ex", e.getMessage().toString());
}
itemList.add(item);
} while (cursor.moveToNext());
}
}
}catch(SQLException ex){
Log.d("DB", ex.getMessage().toString());
}
The challenge?
When I put the params for post, I also set one Param to File as I want to upload an image file as well. I know how to send one object as JSON. I want to POST the list of items (items having image Files). How to achieve this?
One way is that I do an API POST for each object in the list. Not sure if it is a good way to do it.
Looking for advice.
You can post json using this way
JSONObject json = new JSONObject();
json.put("obj", "obj value");
StringEntity entity = new StringEntity(json.toString());
client.post(context, url, entity, "application/json",
responseHandler);
Use this code to send Json data
try{
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("projectid","1");
jsonObject.accumulate("cnumber", "8983899383");
jsonObject.accumulate("address","IN");
jsonObject.accumulate("companyid","5");
jsonObject.accumulate("uploadimage","");
jsonObject.accumulate("id","9")
data = jsonObject.toString();
Log.d("json data",data);
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(CHECK_WEBSERVICE_URL);
StringEntity se = new StringEntity(data);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();

Socket closed exception when trying to read httpResponse

I have a method to connect to send post data to a webservice and get the response back as follow:
public HttpResponse sendXMLToURL(String url, String xml, String httpClientInstanceName) throws IOException {
HttpResponse response = null;
AndroidHttpClient httpClient = AndroidHttpClient.newInstance(httpClientInstanceName);
HttpPost post = new HttpPost(url);
StringEntity str = new StringEntity(xml);
str.setContentType("text/xml");
post.setEntity(str);
response = httpClient.execute(post);
if (post != null){
post.abort();
}
if (httpClient !=null){
httpClient.close();
}
return response;
}
Then, in my AsyncTask of my fragment, I try to read the response using getEntity():
HttpResponse response = xmlUtil.sendXMLToURL("url", dataXML, "getList");
//Check if the request was sent successfully
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// Parse result to check success
responseText = EntityUtils.toString(response.getEntity());
if (!xmlParser.checkForSuccess(responseText, getActivity())){
//If webservice response is error
///TODO: Error management
return false;
}
}
And when I reach that line:
responseText = EntityUtils.toString(response.getEntity());
I get an exception: java.net.SocketException: Socket closed.
This behavior doesn't happen all the time, maybe every other time.
Just write
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(your url);
HttpResponse response = client.execute(post);
it should work.No need to write codes which makes confusion.
I also experienced the 'socket closed' exception when using a client instance built using HttpClientBuilder. In my case, I was calling HttpRequestBase.releaseConnection() on my request object within a finally block before processing the response object (in a parent method). Flipping things around solved the issue... (working code below)
try {
HttpResponse response = httpClient.execute(request);
String responseBody = EntityUtils.toString(response.getEntity());
// Do something interesting with responseBody
} catch (IOException e) {
// Ah nuts...
} finally {
// release any connection resources used by the method
request.releaseConnection();
}

Trouble sending JSON Post Android

It has been a while since I programmed for Android and I have lost all my previous work which had the code in it I am having problems with. I am developing an app for both Android and iPhone which connect to the same server to download data. All is well in the iPhone version but on Android when I hit the server with the post data containing the method name I would like to to run on the server it seems that the data is not added to the request.
Why is the POST not working in this request for Android but does for the iPhone version of the app?
Here is the code I am using:
public static void makeRequest() throws Exception {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);
HttpResponse response;
HttpEntity entity;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
json.put("method", "getEventListData");
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
entity = response.getEntity();
String retSrc = EntityUtils.toString(entity);
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
else{
}
} catch(Exception e) {
e.printStackTrace();
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
The response I get mack from the server is:
{"data":{"scalar":""},"SC":405,"timestamp":1363788265}
Meaning the method name was not found, i.e. not posted in my request to the server.
heres an example of how i do things like this:
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://divisi.co.uk/rest/requesthandler.php");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart(new FormBodyPart("method", new StringBody("getEventListData")));
reqEntity.addPart(new FormBodyPart("NEED_A_KEY_HERE", new StringBody("" + json.toString())));
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
JSONObject responseDict = new JSONObject(EntityUtils.toString(response.getEntity()));
allow this is your "http://divisi.co.uk/rest/requesthandler.php" page code, then in android you can use this... you don't allow post in your URL,
use fiddler on your sever side. see if the http message is correct. it seems your sever side problem, can you show us your sever side code which receive and parse json.
If the server can't read your request try to remove:
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
It will use the mime type defaults HTTP.PLAIN_TEXT_TYPE i.e. "text/plain".
I don't see any other possibility, if your code is the one you posted and not a more complicated input JSON object.
Your code to set the POST body may be just fine. I think the problem may be with your web service. Try using something like Rested or curl to manually make the call to your server. I made exactly the same request you are making, including with and without the POST body, and I got the same response from your server:
{"data":{"scalar":""},"SC":405,"timestamp":1365704082}
Some things that may be tripping you up:
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
if(result.getString("SC") == "200"){
JSONArray data = result.getJSONArray("data");
}
Here, you are comparing the string "405" to "200" using ==, when you should first do a null check and then use .equals("200") instead. Or, use result.getInt("SC") == 200 since this is an integer type in your response JSON.
Also, the "data" entity from your server response is not actually coming back as a JSON array. You should use getJSONObject("data") instead.
Additionally, it's always a good idea to externalize your strings.
Here's how the code should look:
public static final String JSON_KEY_SC = "SC";
public static final String JSON_KEY_DATA = "data";
...
JSONObject result = new JSONObject(retSrc); //Convert String to JSON Object
String sc = result.getString(JSON_KEY_SC);
if (sc != null && sc.equals("200")) {
JSONObject data = result.getJSONObject(JSON_KEY_DATA);
}
else {
...
}

Posting a JSONArray to WCF Service from android

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

Error Android - received HTML instead of JSON

I'm working on a Android application and I'm trying to get a JSON response from a server which is configured to return a json object (".../current_user.json") when receives a GET message, but the answer I get is in HTML format and not in JSON format as expected.
I don't understand why is this happening because I did the same requests on the browser and with the program RESTClient and got the right answer in JSON format.
Here is the code I'm using.
JSONObject json = new JSONObject();
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(params, 10000);
HttpClient httpClient = new DefaultHttpClient(params);
HttpGet get = new HttpGet(url_getiduser);
HttpResponse response = httpClient.execute(get);
String sresponse = "error";
Log.d("url get", url_getiduser);
Log.d("pedido get", get.getMethod());
if(response != null)
{
InputStream in = response.getEntity().getContent();
sresponse = convertStreamToString(in);
Log.d("resposta http", sresponse);
if(!sresponse.equals("error"))
{
JSONObject object = new JSONObject(sresponse);
id_user = (String) object.get("id");
json = object;
Log.d("objecto json", object.toString());
}
else Log.d("Error on json parser", sresponse);
There are few cases where you get HTML text
You might have called a wrong function which gives a 404 page.
Might be a database error on server side where you will get database error message
Server might be sending a styled data which has HTML tags
But you better Log the response and paste it here.

Categories

Resources