Android HttpURLConnection POST没有数据发送

时间:2016-05-27 00:50:36

标签: android asp.net json post httpurlconnection

我在localhost上运行ASP.net JSON服务。我从Android应用程序向服务器发送JSON POST请求。服务器正在接收连接,但没有POST数据(我通过设置断开点来确认这一点,该断点在我从Android应用程序发出POST后命中)。我得到的HttpURLConnection响应代码是200 OK。但是,服务器未接收数据。我不确定是否正在发送任何数据。我的android代码是(包含在AsyncTask中):

public void makeHttpRequest(String verb, String serverAddr, String postBody)
    {
        HttpURLConnection urlConnection = null;
        OutputStream out = null;
        try {
            serverAddr = "http://10.0.2.2:4617/parent/dummy";
            URL url = new URL(serverAddr);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Transfer-Encoding","chunked");
            urlConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

            urlConnection.connect();

            out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(postBody.getBytes("UTF-8"));

            int responseCode = urlConnection.getResponseCode();
            System.out.println("HTTP Response Code: " + responseCode + " | " + urlConnection.getResponseMessage());
        }
        catch (MalformedURLException mal) {
            //
        }
        catch (IOException ioe) {
            //
        }
        finally {
            if (out != null) {
                try {
                    out.close();
                } catch(IOException e) {

                }
            }

            if (urlConnection != null)
                urlConnection.disconnect();
        }

    }

C#/ ASP.NET服务合同。 Parent的实例为null,但应包含POST发送的数据:

[ServiceContract]
    public interface IRestServiceParent
    {

        [WebInvoke(UriTemplate = "{dummy}", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        Parent PostParent(string dummy, Parent instance);
    }

public Parent PostParent(string dummy, Parent instance)
        {
            var result = MasterStorageStore.Instance.PostParent(instance);
            if (result == null) return emptyParent;

            return NewCopy(result);
        }

2 个答案:

答案 0 :(得分:1)

也许您应该尝试在out.flush();之后添加out.write(postBody.getBytes("UTF-8"));

答案 1 :(得分:0)

我通过一个简单的PHP脚本发现,尽管设置了setRequestMode("POST")setDoOuput(true)HttpURLConnection仍被GET而不是POST发送。我不知道为什么。