我尝试将HTTP Post Request从Android应用程序发送到C#RESTful Web服务。 出于某种原因,我会在连接后立即收到响应代码405。
如果我尝试使用我制作的C#客户端发送POST请求,代码工作正常,我成功得到了响应。
来自Android的代码(在服务中运行):
String url = "http://myurl.com/Service1.svc/login/2";
String postDataParams = "{"username":"Ryrud","password":"Pups"}";
//Connect
httpcon = (HttpURLConnection) ((new URL(url).openConnection()));
int responseCode = httpcon.getResponseCode();
Log.d("zzz", "RCode: " + responseCode); // Getting in log: "RCode: 405"
httpcon.setDoOutput(true);
httpcon.setRequestMethod("POST");
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.connect();
//Post data
DataOutputStream wr = new DataOutputStream(httpcon.getOutputStream());
wr.writeBytes(postDataParams);
wr.flush();
wr.close();
RESTful Web服务代码:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "login/{id}")]
login login(string id, login userpass);
答案 0 :(得分:0)
在将数据写入输出流之前,不要询问响应代码。