我用C#编写了一个简单的WCF Restful web服务,以获得一些参数的值。这是我的I服务代码:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string GetURL(string pVr);
这是Service.svc 的代码
public string GetURL(string pVr)
{
try
{
string VersionCode = ConfigurationManager.AppSettings["MobAppVersionCode"];
if (Convert.ToInt32(VersionCode) > Convert.ToInt32(pVr))
{
return "http://xxx.xxx.xxx.xxx/abc.apk";
}
else
{
return "No apk available";
}
}
catch (Exception ex)
{
throw ex;
}
}
我的目的之一是,当我将这个web服务发布到IIS时,该方法应该被隐藏(不再有rest、帮助页或wsdl),这样我就可以更改web配置并设置为这样的
<behaviors>
<serviceBehaviors>
<behavior name="SEILServiceBehaviour">
<serviceMetadata httpGetEnabled="false" httpsGetEnabled="false" />
<serviceDebug includeExceptionDetailInFaults="false" httpHelpPageEnabled="false" httpsHelpPageEnabled="false" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp helpEnabled="false"/>
</behavior>
</endpointBehaviors>
</behaviors>
现在,在将此web服务发布到IIS中后,我可以通过邮递员或web浏览器轻松地看到服务结果,甚至可以通过Reformation2 android库获取数据。但是当我用HttpUrlConnection代码连接这个web服务时,它会向我显示错误405 Method Not Allowed。这是我的连接页面的代码
public void onRequest(String urlParameters) {
try {
//Establishing connection with particular url
URL url = new URL("http://xxx.xxx.xxx.xxx/Service.svc/GetURL");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//Setting connection timeout
connection.setReadTimeout(30000);
connection.setConnectTimeout(30000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
InputStream inputStream;
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK)
inputStream = connection.getErrorStream();
else
inputStream = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
String line;
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('r');
}
rd.close();
if (url.getHost().equals(connection.getURL().getHost())) {
urlReceive = response.toString().trim();
} else {
urlReceive = "Internet Login Required";
}
} catch (IOException e) {
urlReceive = "Connection Timed Out";
}
}
请帮我
您的请求需要是GET
,根据:
[WebInvoke(Method = "GET",
您正在使用POST
:
connection.setRequestMethod("POST");
您需要更改代码以使用GET
请求,而不是POST
。