将数据传递到 .net Web 服务并获取结果

本文关键字:服务 获取 结果 Web net 数据 | 更新日期: 2023-09-27 18:33:29

我需要关于如何将输入数据从Android传递到.net Web服务以及将结果检索到Android应用程序的有效示例/教程。

请分享您可能认为与我的需求相关的指南、示例、教程的任何链接。

将数据传递到 .net Web 服务并获取结果

你可以创建一个Rest Web服务,这里有一个教程,你可以使用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);

然后,在托管您的网络服务之后,您需要使用 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();

之后,您应该在"结果"中有一个字符串,此字符串表示您的响应(JSON 或 XML)。

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

这里给出一个小样本,试试这个帖子

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();
        }
    }