将数据传递给.NET Web服务并获取结果?

4

我需要一个有效的示例或教程,说明如何将Android输入数据传递到.net Web服务,并从Android应用程序检索结果。

请分享任何与我的需求相关的指南、示例或教程链接。

2个回答

1

您可以创建一个Rest Webservice,这里有一个教程,您可以使用URI传递输入数据,并且您应该计划您的URI应该如何,例如发布客户名称:

        [OperationContract]
        [WebInvoke(Method = "POST",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/post-customer/{name}")]
        void postCustomer(string name);

使用客户ID获取客户数据:

        [OperationContract]
        [WebInvoke(Method = "GET",
            ResponseFormat = WebMessageFormat.Json,
            BodyStyle = WebMessageBodyStyle.Wrapped,
            UriTemplate = "json/get-customer/{id}")]
        Customer getCustomer(string id);

然后,在托管您的 Web 服务之后,您需要使用 HTTP 客户端从 Android 应用程序访问它,例如:

String uri = "uri to your service";
HttpClient httpclient = new DefaultHttpClient();  
HttpGet request = new HttpGet(uri);  
ResponseHandler<String> handler = new BasicResponseHandler();  
String result = null;
try {  
    result = httpclient.execute(request, handler);  
} catch (ClientProtocolException e) {  
    e.printStackTrace();  
} catch (IOException e) {  
    e.printStackTrace();  
}  
httpclient.getConnectionManager().shutdown();

接下来,您应该在“result”中拥有一个字符串,该字符串代表您的响应(JSON或XML)。

希望这些信息能对您有所帮助。


0

这里提供一个小样例,请尝试使用以下代码进行提交:

public void post(String appid,String custlogid,String cityareaid,String mosqname,String mosqid,String lat,String lon){

        HttpClient httpclient = new DefaultHttpClient();   
        HttpPost httppost = new HttpPost(globalconstant.URL_mosquepost); 
        UrlEncodedFormEntity form;
        // Add your data   
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(6);   
        nameValuePairs.add(new BasicNameValuePair("APPUDID", appid));
        nameValuePairs.add(new BasicNameValuePair("CUSTLOGID", custlogid));
        nameValuePairs.add(new BasicNameValuePair("CITYAREAID", cityareaid));
        nameValuePairs.add(new BasicNameValuePair("CITYMOSQUENAME", mosqname));
        nameValuePairs.add(new BasicNameValuePair("CITYMOSQUEID", "0"));
        nameValuePairs.add(new BasicNameValuePair("LATITUDE", lat));
        nameValuePairs.add(new BasicNameValuePair("longitude", lon));
        try {
            form = new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
             httppost.setEntity(form);
            Log.d("myapp", "works till here. 2");
            try {
                HttpResponse response = httpclient.execute(httppost);
                Log.d("myapp", "response " + response.getStatusLine().getStatusCode()+"\n"+EntityUtils.toString(response.getEntity()));

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接