首页 > 解决方案 > UWP 客户端 PUT 和 POST 请求使用 PHP API 失败

问题描述

当我尝试发送帖子并将请求发送到我的 webapi 时遇到问题(服务器端用 php 编码并与 mysql 一起使用)。

如果我尝试发送 get 请求根本没有问题,API 会正确响应,当我尝试在请求中发送正文时问题就来了(这就是我认为 post 和 put 失败的原因)。

我确信我的 api 运行良好,只要我对邮递员和其他客户进行了测试,并且他们都按照正确的方式处理这些请求。API 响应 400 Bad Request,我不知道该怎么做。我用 C# 编写了相同的 api,我的代码在客户端工作,通用 Windows 平台和 PHP API 之间有什么不兼容吗?

我的 PUT 方法:

public async Task<int> updateFestivalDAL(Festival festival)
    {
        int resultado = 0;
        Uri miConexion = (new clsMyConnection().getConnection());
        HttpClient miCliente = new HttpClient();
        String body = "";
        HttpStringContent contenido;
        HttpResponseMessage miRespuesta = new HttpResponseMessage();
        try
        {

            body = JsonConvert.SerializeObject(festival);

            contenido = new HttpStringContent(body, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");
            miRespuesta = await miCliente.PutAsync(new Uri(miConexion + "/" + festival.ID), contenido);
            if (miRespuesta.IsSuccessStatusCode)
            {
                resultado = 1;
            }
        }
        catch (SqlException e)
        {
            throw e;
        }
        return resultado;
    }    

这是我请求的身体:

"{\"ID\":1,\"edicion\":\"Prueba año anterior\",\"nombre\":\"fgh\",\"fecha_inicio\":\"2017-10-01T00:00:00\",\"fecha_fin\":\"2017-10-03T00:00:00\",\"coordenadas\":\"asdf\",\"twitter\":\"\",\"facebook\":\"\",\"instagram\":\"\",\"web\":\"\",\"curiosidades\":\"\"}"    

这就是我的 API 响应(miRespuesta 变量值):

 {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 2, Content: 
    Windows.Web.Http.HttpStreamContent, Headers:
    {
    Connection: close
    Server: Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/5.6.38
    Date: Wed, 31 Oct 2018 21:47:36 GMT
    X-Powered-By: PHP/5.6.38
   }{
   Content-Length: 0
   Content-Type: text/html; charset=UTF-8
   }}

如果你知道什么,请帮助我。

更新:当我看到 miCliente 变量(带有 httpclient 的变量)的内容时,我可以看到一个名为 DefaultRequestHeaders 的列表元素。也许有问题?我必须编辑这些以使它们与 PHP 兼容?

更新 2: 我已经更改了数据库和我的 Festival 类中的两个日期元素(fecha_inicio、fecha_fin),所以它们现在是 varchar(类中的字符串),如果问题是解析日期时间并尝试在数据库中保存为日期,但仍然不行。

邮递员成功请求:

PUT /festival/1 HTTP/1.1
Host: notrelevantbutwellformed.com
Content-Type: application/json
cache-control: no-cache
Postman-Token: 100313d6-7087-4712-8b93-17873e1db14b
{
    "ID": "1",
    "edicion": "fgh",
    "nombre": "fgh",
    "fecha_inicio": "2018-11-01",
    "fecha_fin": "2018-11-01",
    "coordenadas": "asdf",
    "twitter": "asfd",
    "facebook": "ffsd",
    "instagram": "asrss",
    "web": "noo va a petar",
    "curiosidades": "sdfsdfdsf",
    "url_logo": "",
    "url_cartel": ""
}------WebKitFormBoundary7MA4YWxkTrZu0gW--    

标签: c#uwpputbad-request

解决方案


推荐阅读