Program Admin Program Admin - 8 days ago 6
Android Question

Restful wcf service returns data rows in json - android client

I have a created a WCF service which is consumed by android. It returns DataRows in json. As,

Web.config

<?xml version="1.0"?>
<configuration>

<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="httpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>

<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfAndroid.Service1">
<endpoint address=""
behaviorConfiguration="httpBehavior"
binding="webHttpBinding"
contract="WcfAndroid.IService1" />

</service>
</services>
<protocolMapping>
<add binding="webHttpBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>

</configuration>


Service Interface IService1 :

<OperationContract()> _
<WebInvoke(Method:="POST", UriTemplate:="GetEmp", ResponseFormat:=WebMessageFormat.Json)> _
Function GetEmp(ByVal EmpId As String) As DataTable


Service Class Service1 :

Public Function GetEmp(ByVal EmpId As String) As DataTable
Dim table As New DataTable("mytable")
table.Columns.Add("Result", GetType(String))
table.Columns.Add("acc", GetType(String))
table.Columns.Add("name", GetType(String))
table.Columns.Add("paid", GetType(Double))
'' Using EmpId for Fetching data from Database

table.Rows.Add("True", "1", "Employee1", 5000)
table.Rows.Add("True", "2", "Employee2", 2000)

Return table
End Function


EmpId is unique id for every employee. I am getting the details from Sql Server database. For testing i have sent 2 rows manually.

In android app for WebGet i have used :

public static JSONObject requestWebService(String serviceUrl) {
HttpURLConnection urlConnection = null;
try {
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection)
urlToRequest.openConnection();

int statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// handle unauthorized
} else if (statusCode != HttpURLConnection.HTTP_OK) {
// handle any other errors
}

InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
String ss=getResponseText(in);
return new JSONObject(ss);

} catch (MalformedURLException e) {

// URL is invalid
} catch (SocketTimeoutException e) {

// data retrieval or connection timed out
} catch (IOException e) {

// could not read response body
// (could not create input stream)
} catch (JSONException e) {

// response body is no valid JSON string
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}

return null;
}


But i don't know how to POST with EmpId and getDataRows.

I have to consume this service in android app. I am using HttpURLConnection.

How to post using HttpURLConnection and getDatarows (json format) ?

Answer

You can use OutputStreamWriter as :

  public static JSONObject PostWebService(String serviceUrl) {
   HttpURLConnection urlConnection = null;
    try {
        // create connection
        URL urlToRequest = new URL(serviceUrl);
        urlConnection = (HttpURLConnection)
                urlToRequest.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");


        OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
        out.write("EmpID2016");
        // You can write json also // Uncomment
        //  JSONObject jsonParam = new JSONObject();
      //  jsonParam.put("EmpID", "25");
      //  jsonParam.put("description", "Employer");
      //  jsonParam.put("authorized", "true");
      //  out.write(jsonParam.toString());
        out.close();

        int statusCode = urlConnection.getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // handle unauthorized (if service requires user login)
        } else if (statusCode != HttpURLConnection.HTTP_OK) {
            // handle any other errors, like 404, 500,..
        }

        // create JSON object from content
        InputStream in = new BufferedInputStream(
                urlConnection.getInputStream());
        String ss=getResponseText(in);
        return new JSONObject(ss);

    } catch (MalformedURLException e) {

    } catch (SocketTimeoutException e) {

    } catch (IOException e) {

    } catch (JSONException e) {
               // response body is no valid JSON string
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    return null;
}