gpt4 book ai didi

Android HttpURLConnection POST 没有数据被发送

转载 作者:行者123 更新时间:2023-11-30 01:18:32 24 4
gpt4 key购买 nike

我在本地主机上运行 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);
}

最佳答案

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

关于Android HttpURLConnection POST 没有数据被发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37473169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com