我是使用WCF框架开发的C#webservice的新手。我必须在URL中发布数据。我的网址类似于 http://www.example.com/abc/DGLC.svc/login ,我必须使用post方法传递数据。参数如下格式。
{
“UserName”:“Admin”,
“密码”:“abcd1234”,
“DiviceType”:“Windows”,
“UniqueID”:“deviceidneedtopasshere”
}
请帮助我,如何实现这种WS。提前谢谢。
答案 0 :(得分:0)
创建一个表示json字段的类。并在您的webservice中传递方法参数。并在您的反向线程(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;
}
其中data是json对象的新字符串new JsonObject.accumulate()... etc,用于映射服务对象