[英]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.