[英]WCF service Android connection
我对android和wcf服务太陌生了。 我有一个期望。
这是android函数:
private void Post(String VAL)
{
HttpClient httpClient = new DefaultHttpClient();
try
{
String aaa = "aaa";
String url = "http://192.168.30.117:59151/IService1";
HttpPost method = new HttpPost(url);
StringEntity e = new StringEntity("{ \"something\":12345 }", "UTF-8");
method.setEntity(e);
method.setHeader("content-type", "application/json");
method.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(method);
HttpEntity entity = response.getEntity();
if(entity != null)
{
System.out.println(entity);
}
} catch (IOException e) {
Log.e( "error", e.getMessage() );
}}
这是WCF的一部分:
[ServiceContract()]
public interface IService1
{
[OperationContract]
[WebInvoke(Method= "POST", UriTemplate = "GetData?parameter={parameter}", ResponseFormat = WebMessageFormat.Json)]
string GetData(string parameter);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
public string GetData(String value)
{
return string.Format("You entered: {0}", value);
}
这是配置文件:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2"/>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="http_behavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="http_behavior" name="WcfServiceGps.Service1">
<endpoint address="" binding="webHttpBinding" bindingConfiguration=""
name="GetData" contract="WcfServiceGps.IService1" />
<endpoint address="mex" binding="mexHttpBinding" name="GetDataMex"
contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://192.168.30.117:59151/Service1.svc/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<directoryBrowse enabled="true"/>
</system.webServer>
当我从android调用服务时
HttpResponse response = httpClient.execute(method);
它给出以下异常:
如果您使用虚拟机在android上编译应用,则必须在服务器上具有可见性,与使用虚拟机时相同。 您之所以会遇到这种异常,是因为您的设备不在同一网络中,而且似乎您没有在部署服务器,只是在Visual Studio上对其进行了编译……这是什么? '59151'IIS Express的端口号?
在Windows上下载IIS并部署服务器,然后使用ipconfig命令了解本地网络中的IP地址,这通常是尝试使用Android浏览器与服务器连接(编写IP 192.168.XX)。 如果可行,请尝试在android浏览器中调用REST服务,如果可行,您现在可以在android中测试REST调用。
顺便说一下,将Retrofit 2用作REST库。
如果您在主线程中调用api,请不要这样做。 使用AsyncTask消耗api。 并将这些行放入您的活动中或将您使用的内容片段化。
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.