我阅读了很多教程,但我无法为我的项目运行它。我做了一些发送数据的 GET 服务,它们工作得很好,但是我在接收数据时遇到了问题。如果有人能告诉我我失败的地方,而不是发布一些链接,我将不胜感激。:) 当我尝试在浏览器中调用该服务时,出现错误:不允许使用方法。但我认为这只是第一个错误。
这是我的代码。首先是我调用服务的Android代码:
public class MainActivity extends Activity {
String SERVICE_URI = "http://10.0.2.2:51602/RestServiceImpl.svc";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HttpPost request = new HttpPost(SERVICE_URI + "/registerUser");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
try {
JSONStringer user = new JSONStringer()
.object()
.key("userInfo")
.object()
.key("Email").value("mail")
.key("Password").value("pass")
.key("Cauntry").value("country")
.key("UserName").value("username")
.endObject()
.endObject();
StringEntity entity = new StringEntity(user.toString());
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
IRestServiceImpl.cs:
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "registerUser",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
void receiveData(String data);
}
RestServiceImpl.cs:
public class RestServiceImpl : IRestServiceImpl
{
public void receiveData(String data)
{
//some code
}
}
网络配置:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="RestService.RestServiceImpl" behaviorConfiguration="ServiceBehaviour">
<endpoint address ="" binding="webHttpBinding" contract="RestService.IRestServiceImpl" behaviorConfiguration="web">
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>