我创建了一个asp.net Web服务,它有两个方法,第一个是getBoughtApps(String imei)
另一个是getAllApps()
。服务名称为ArttechApps
。我需要一个使用java或android调用这些方法的代码
有谁可以帮助我?
答案 0 :(得分:3)
您应该编写一个middlieware服务,将xml或json返回给您的客户端。
使用reciever.aspx在您的iis上创建一个新的Web项目
清除您的aspx文件代码,只剩下
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="reciever.aspx.cs" Inherits="reciever" %>
然后是您的代码页(.cs文件)
将您的服务添加到此项目
on pageload
if (Request.QueryString["ID"] != null)
{
string id = Request.QueryString["id"]; // ID paremeter will be taken from your client.I will explain.
if (id == "getBoughtApps")
{
string imei= Request.QueryString["imei"];
// IMEI paremeter 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 quaerystring 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);
}
}
答案 1 :(得分: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的内容取决于您服务的界面。将参数值放入对象,然后从此方法重新捕获的对象中读取回复值。
答案 2 :(得分: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;
}