In Android, how to send data to the webservice that is created in WCF?

I am new to C # webservice developed using WCF. And I need to send data to the url. My url is like http://www.example.com/abc/DGLC.svc/login and I have to pass data using the post method. And the parameters follow in the following format.

{

"UserName": "Admin",

"Password": "abcd1234",

"DiviceType": "Windows",

"UniqueID": "deviceidneedtopasshere"

}

Please help me how to implement such a WS. Thanks in advance.

+1
source share
1 answer

create a class representing the fields of your json. and in your web service pass this in the method parameter. and run this method in your backthread (asyncTask)

public static String postAPIResponse(String url, String data) { HttpURLConnection con = null; InputStream inputStream; StringBuffer responses = null; try { URL urlObject = new URL(url); con = (HttpURLConnection) (urlObject.openConnection()); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); con.setRequestProperty("Content-Length", Integer.toString(data.getBytes().length)); con.setRequestProperty("Content-Language", "en-US"); if (Cookie.getCookie() != null) con.addRequestProperty("Cookie", Cookie.getCookie()); con.setUseCaches(false); con.setDoInput(true); con.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(data); wr.flush(); wr.close(); //Get Response if (con.getResponseCode() == 200) { InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; responses = new StringBuffer(); while ((line = rd.readLine()) != null) { responses.append(line); } rd.close(); } else { inputStream = new BufferedInputStream(con.getErrorStream()); return convertInputStreamToString(inputStream); } } catch (Exception e) { e.printStackTrace(); } finally { assert con != null; con.disconnect(); } return responses != null ? responses.toString() : ""; } static public String convertInputStreamToString(InputStream inputStream) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; String result = ""; while ((line = bufferedReader.readLine()) != null) { result += line; } /* Close Stream */ inputStream.close(); return result; } 

where the data is a json new object string JsonObject.accumulate () ... etc. to map to your service object

+1
source

All Articles