0

I have to send/post some data to .svc Web Service that basically connect to remote database. I'm using JSONStringer to send the data but every time response status is false. My data is not sent. How to use HttpPost in Android . Can someone help me how to solve this .

Here is my webservice code

String namespace = "http://103.24.4.60/xxxxx/MobileService.svc";

public void ActivityUpload( final String strCurrentDateTime, final String strTitle, final String replaceDescChar, final String editedHashTag)
    {
        new AsyncTask<String, Void, String>()
        {
            @Override
            protected String doInBackground(String... arg0)
            {
                 String line = "";
                try
                {
                    Log.e("ActionDate "," = "+ strCurrentDateTime);
                    Log.e("ActivityId"," = "+strActivityId);
                    Log.e("UserId"," =  "+str_UserId);
                    Log.e("ObjectId"," = "+strVessId);
                    Log.e("Name"," = "+strTitle);
                    Log.e("Remark"," = "+replaceDescChar);
                    Log.e("Status"," = "+"PENDING");
                    Log.e("Type"," = "+strType);
                    Log.e("starflag"," = "+0);
                    Log.e("HashTag"," = "+editedHashTag);
                    Log.e("Authentication_Token"," = "+str_Authentication_Token);


                    // make web service connection
                    HttpPost request = new HttpPost(namespace + "/Upd_Post_Activity");
                    request.setHeader("Accept", "application/json");
                    request.setHeader("Content-type", "application/json");
                    // Build JSON string
                    JSONStringer TestApp = new JSONStringer().object()
                                .key("ActionDate").value(strCurrentDateTime)
                                .key("ActivityId").value(strActivityId)
                                .key("UserId").value(str_UserId)
                                .key("ObjectId").value(strVessId)
                                .key("Name").value(strTitle)
                                .key("Remark").value(replaceDescChar)
                                .key("Status").value("PENDING")
                                .key("Type").value(strType)
                                .key("starflag").value("0")
                                .key("HashTag").value(editedHashTag)
                                .key("Authentication_Token").value(str_Authentication_Token).endObject();
                    StringEntity entity = new StringEntity(TestApp.toString());

                    Log.d("****Parameter Input****", "Testing:" + TestApp);
                    request.setEntity(entity);
                    // Send request to WCF service
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpResponse response = httpClient.execute(request);

                    Log.d("WebInvoke", "Saving: " + response.getStatusLine().toString());
                    // Get the status of web service
                    BufferedReader rd = new BufferedReader(new InputStreamReader(
                            response.getEntity().getContent()));
                    // print status in log

                    while ((line = rd.readLine()) != null) {
                        Log.d("****Status Line***", "Webservice: " + line);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return line;
                 }

        }.execute();
    }

Here is input Parameter.

****Parameter Input****﹕ Testing:{"ActionDate":"2016-01-21%2014:20:43%20PM","ActivityId":"120160119180421058","UserId":"125","ObjectId":"1","Name":"Title2","Remark":"Test%20two","Status":"PENDING","Type":"3","starflag":"0","HashTag":"990075","Authentication_Token":"6321D079-5B28-4F3F-AEE7-D59A1B9EFA59"}

Thanks in advanced.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
p. ld
  • 585
  • 3
  • 10
  • 23
  • maybe you could give use also your WS url to try and see if there is no problem in your WS. – To Kra Jan 21 '16 at 09:04
  • It is recommended to avoid using [HttpClient](http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client). It is deprecated. An excellent alternative is [OkHttp](http://square.github.io/okhttp/), which has a lot of "[recipes](https://github.com/square/okhttp/wiki/Recipes)" to get you started. – Knossos Jan 21 '16 at 09:38
  • No any problem in WS. – p. ld Jan 21 '16 at 09:38

1 Answers1

0

realize android httpclients are in process of deprecation ( in favor of httpsurlconnection ) but, these httpclients are still used pretty widely. On gradle builds, regard the deprication, and with small dependency lib tweeks , httpclient may be used for some time still.

( still gonna use httpclient ? )

Put android aside for a min.

  1. learn how to CURL with JSON body for tests that show you what you EXACT JSON in body and exact HEADERS you will need to get success http result to a post ... ref here

Once you have that you can then go about transferring your curl test's components over to android.httpclient.exec.POST using httpclient of your choice.

  1. Set the same group of Headers you had over in curl tests in your android post. apache.httpclient sample

2.a. make sure that default list of headers from the clients 'request' constructor does NOT include by default some headers you DO NOT want... In order to assure of this ,you probably will need to turn on HEADER logging for your client.... java example logger . remove unnecessary headers included by the framework constructor of POST.

2.b android logger (WIRE, HEADERS) is diff from and may take some digging , depend on what client is in use.

  1. with the same headers as curl tests, set the http.posts request.entity to either a string or a properly encoded array of bytes containing the same JSON body used in the curl tests.

3.A. depending on the JSON lib, create your message objects and then convert the objects to some friendly type for enclosure in an entity for the post ie use a 'writer' to convert objects to a serialized string with the JSON.

       reqRole = new ObjectMapper().createObjectNode();
        reqRole.put("__type", "Pointer");
        reqRole.put("className", "_Role");
        reqRole.put("objectId", roleId);
        rootOb.put("requestedRole", reqRole);
        rootOb.put("requestedBy",usersArr);
        StringWriter writer = new StringWriter();
        try {
            new ObjectMapper().writeValue(writer, rootOb)
..
         String http-post-str=writer.toString(); 

3.B. wrap the string with json in the POST request...

httpPost.setEntity(new StringEntityHC4(http-post-str)); 
  1. exec the request and youll get the same results you got in curl because the headers are same or nearly same and the body is the same , encoded string of json. same input = same result
Community
  • 1
  • 1
Robert Rowntree
  • 6,230
  • 2
  • 24
  • 43