我正在创建一个Messenger应用程序,当前在客户端上运行,并且我已经对大多数API(服务器端)进行了编程。
我正在尝试向服务器发送POST请求,但是它将\r\n
放在数据包的每个元素之后(例如:-,content-type header = application/json\r\n
)
这意味着当我的服务器尝试验证传入流量是否为JSON格式时,它会将其丢弃。
我已经使用WireShark来查看数据包的外观,这是屏幕截图:
我用来发送请求的代码:
using Newtonsoft.Json;
using System.Net.Http;
public async static Task<HttpResponseMessage> PostRequestAsync(string path, object data)
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(Main.ServerAddress + ":" + Main.ServerPort.ToString() + path),
Method = HttpMethod.Post,
};
MessageBox.Show("Content: " + JsonConvert.SerializeObject(data));
request.Content = new StringContent(JsonConvert.SerializeObject(data));
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
MessageBox.Show(request.ToString());
var response = new HttpResponseMessage();
using (HttpClient client = new HttpClient())
{
response = await client.SendAsync(request);
}
return response;
}
被序列化为json的对象/已发送到服务器:
public class UserCreds{
public string username;
public string password;
}
谢谢。
这是服务器代码:
@server.route("/1/signup", methods=["POST"]) # Sign up a user.
def sign_up_user():
if request.is_json == False:
return make_response(), 400
userJson = request.get_json()
uName = userJson['username']
pWord = userJson['password']
#try:
file = open(userCredsFile, 'r')
fileRaw = file.read()
creds = {}
if fileRaw != "":
creds = json.loads(fileRaw)
if uName in creds:
return create_status_response("User already exists.")
else:
creds[uName] = pWord
file.close()
file = open(userCredsFile, 'w')
file.write(json.dumps(creds))
file.close();
return make_response(), 201
#except e:
# return create_status_response("Something happened.")