0

我创建了一个 asp.net Web 服务,它有两种方法,getBoughtApps(String imei) 一种是getAllApps(). 服务名称是ArttechApps。我需要一个使用 java 或 android 调用这些方法的代码,任何人都可以帮助我吗?

4

3 回答 3

3

您应该编写一个将 xml 或 json 返回给客户端的中间件服务。

在您的 iis 上使用 receiver.aspx 创建一个新的 Web 项目

清除你的aspx文件代码,只剩下,

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="receiver.aspx.cs" Inherits="receiver" %>

然后是您的代码页(.cs 文件)

将您的服务添加到此项目

在页面加载时

 if (Request.QueryString["ID"] != null)
 {
        string id = Request.QueryString["id"]; // ID parameter will be taken from your client.I will explain.

        if (id == "getBoughtApps")
        {
           string imei= Request.QueryString["imei"];  
           // IMEI parameter will be taken from your client.I will explain.

            // Use your service method here then create an xml and write 
            // look at Example below 

            DataSet ds = SqlHelper.ExecuteDataset(connStr, CommandType.StoredProcedure, sp_Get_BoughtApps"
                , new SqlParameter("@imei", imei));

            string str = @"<?xml version=""1.0"" encoding=""utf-8"" ?><test>";

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                str += "<item>";
                str += "<ID>" + dr["ID"].ToString() + "</ID>";
                str += "<appName>" + dr["appName"].ToString() + "</appName>";
                str += "</item>";
            }

            str += @"</test>";

            Response.Write(str); // it returns an xml and your client will catch it
        }

        if (id == "getAllApps")
        {
              // write your code
        }
    }

在您的客户端:

private class asynGetBoughtApps extends AsyncTask<String, Void, Integer> {
    protected Integer doInBackground(String... params) {
        try {
            final Uri.Builder uri = new Uri.Builder();
            uri.scheme("http");
            uri.authority(ip or domainname); // "127.0.0.1"
            uri.path(alias name ); // "android/reciever.aspx"
            uri.appendQueryParameter("id", "getBoughtApps"); // you can sent querystring with this
            uri.appendQueryParameter("imei", "35464545454");


            URL url = new URL(uri.toString());
            DocumentBuilderFactory dbf = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(new InputSource(url.openStream()));
            doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("item"); // xml node which will loop in

            for (int i = 0; i < nodeList.getLength(); i++) {
                
                Node node = nodeList.item(i);
                Element fstElmnt = (Element) node;

                NodeList nodelist = null;
                Element element = null;
                
                nodelist = fstElmnt.getElementsByTagName("ID"); 
                element = (Element) nodelist.item(0);
                nodelist = element.getChildNodes();
                if ((nodelist.item(0)) != null)
                    string ID = (nodelist.item(0)).getNodeValue().toString();

                                    nodelist = fstElmnt.getElementsByTagName("appName");
                element = (Element) nodelist.item(0);
                nodelist = element.getChildNodes();
                if ((nodelist.item(0)) != null)
                    string appName= (nodelist.item(0)).getNodeValue().toString();

                
            }
        } catch (Exception e) {             
            return 0;
        }

        return 1;
    }

    protected void onPostExecute(Integer result) {
        try {
            // Now you get data from your server and you can use it in your app
        } catch (Exception e) {             
        }

        super.onPostExecute(result);
    }
}
于 2012-11-14T14:05:43.443 回答
0

您需要知道服务方法的 URI,然后,假设您使用的是 JSON,您的 android 代码可能如下所示:

    public JSONObject webServiceRequest(JSONObject reqJS) throws IOException, JSONException
    {
        HttpPost pr = new HttpPost("http://yourhost.com/path/to/service/method/");
        pr.setHeader("Accept", "application/json"); 
        pr.setHeader("Content-type", "application/json");
        pr.setEntity(new StringEntity(reqJS.toString(), "UTF-8"));

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 20000); 
        HttpConnectionParams.setSoTimeout(httpParams, 20000); 
        HttpClient client = new DefaultHttpClient(httpParams);

        HttpResponse response = client.execute(pr);

        InputStream inps = response.getEntity().getContent();

        StatusLine sl = response.getStatusLine();
        if(sl.getStatusCode() != 200)
        {
            Log.e("TAG", String.format("Error %d reply on request: %s", sl.getStatusCode(), sl.getReasonPhrase()));
            return null;
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(inps));
        StringBuilder sb = new StringBuilder();
        String respLine;
        while((respLine = br.readLine()) != null)
        {
            sb.append(respLine);
        }

        return new JSONObject(sb.toString());
    }

reqJS 的内容取决于您的服务接口。将您的参数值放入对象,然后从该方法返回的对象中读取回复值。

于 2012-11-14T13:57:20.653 回答
0

这是我用来调用ASMX webservices(SOAP)的Ksoap2 soap类,希望对你有用

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Vector;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import android.util.Log;

public class webServices {

    public static String METHOD_NAME;
    public static String NAMESPACE;
    public static String URL;   
    public SoapSerializationEnvelope Envelope_class = null; 
    private SoapObject request;

    public webServices(String NombreMetodo, String Namespace, String URLWService )
    {       
        METHOD_NAME = NombreMetodo;
        NAMESPACE= Namespace;
        URL= URLWService;   
        request= GetSoapObject(METHOD_NAME);
    }

    public void AddProperty(String Name, Object Value ,Type tipo)
    {
        PropertyInfo prop = new PropertyInfo();     
        prop.setName(Name);
        prop.setValue(Value);
        prop.setType(tipo);
        request.addProperty(prop);  
    }

    private SoapObject GetSoapObject (String Methodname)
    {
        return new SoapObject(NAMESPACE,METHOD_NAME);
    }

    private static SoapSerializationEnvelope GetEnvelope(SoapObject Soap)
    {
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       envelope.dotNet = true;     
       envelope.setOutputSoapObject(Soap);
       return envelope;

     }

    public SoapObject CallWebService() throws IOException, XmlPullParserException 
    {       
        SoapObject response=null;
        SoapSerializationEnvelope Envelope = GetEnvelope(request);
        Envelope.bodyOut=request;
        AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);
        androidHttpTransport.debug=true;
        try
           { 

               androidHttpTransport.call(NAMESPACE + METHOD_NAME, Envelope);              
               response = (SoapObject) Envelope.getResponse();      
               Envelope_class = Envelope;
           }
        catch(Exception e)
        {
            e.printStackTrace();
            Log.d("AndroidRequest",androidHttpTransport.requestDump);
            Log.d("AndroidResponse",androidHttpTransport.responseDump);
            return null;
        }   

        return response;
    }

    public Object CallWebServicePrimitive() throws SoapFault
    {
        SoapObject request = GetSoapObject(METHOD_NAME);    
        SoapSerializationEnvelope Envelope = GetEnvelope(request);

         HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
         try {
            androidHttpTransport.call(NAMESPACE + METHOD_NAME, Envelope);
        } catch (IOException e) {
            Log.d("ErrorApp", e.getMessage().toString());
        } catch (XmlPullParserException e) {
            Log.d("ErrorApp", e.getMessage().toString());
        }   

        SoapPrimitive response= (SoapPrimitive) Envelope.getResponse();
        return response;
    }

}

这里有一个调用示例:

public static Provincias[] GetProvincias() throws IOException, XmlPullParserException, NumberFormatException, IllegalArgumentException, IllegalAccessException, InstantiationException
    {
        webServices miws = new webServices("MethodName","http://tempuri.org/",url_web);                                 
            //Add string parameter
        miws.AddProperty("Token",Token,String.class);

        SoapObject respuesta = miws.CallWebService();
        Provincias[] provincias= ParsearProvincias(respuesta);
        return provincias;

    }
于 2012-11-14T14:08:54.520 回答