我有以下代码应该通过 WCF 服务将两个字段插入到数据库中,但是当我在 Eclipse 中测试时出现 405 Method Not Allowed 错误。
WCF 在 Fiddler 和我的测试 C# web 客户端上工作,我只通过手机从 Android 收到错误,这让我相信问题可能出在这段代码中!
HttpPost request = new HttpPost("http://www.mysite.com/myservice.svc/postname?fname=fred&lname=frognoggle");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving : " + response.getStatusLine().getStatusCode());
谁能看到我错过了什么!
编辑
我正在 Fiddler 中发帖,如果我发帖:
http://www.mysite.com/myservice.svc/postname?fname=fred&lname=frognoggle
一切正常。
干杯,
迈克。
最佳答案
更新:应要求返回。下面的代码是我用来在 Android 上制作 JSON POST 的代码,它对我有用。
您正在您的 Android 代码中执行 HTTP POST。你也在 fiddler 中做 POST 还是在做 GET?我问的原因是你没有在你的帖子中发送正文,只是设置查询字符串。我已经包含了我的 Android 代码,它对 WCF 服务执行 JSON POST。
希望这有助于...
如果您发布更多信息,我将很乐意提供帮助并更新答案。
public JSONObject sendPOSTurl(String url, JSONObject data) throws JSONException
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response;
try
{
StringEntity se = new StringEntity(data.toString());
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null)
{
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return new JSONObject(result);
}
}
catch(Exception e)
{
Log.e("REST", "Failed to POST data", e);
}
return null;
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return sb.toString();
}
关于Android WCF 方法不允许,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9371656/