发送http帖子到dot net webapi

时间:2015-09-07 14:43:42

标签: java android http post asp.net-web-api

我有这个问题

  

使用获取

我想发送一篇http帖子

这是我的Android类和请求方法

    public static String readUrl(String url, ArrayList<NameValuePair> params) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);

        if (params != null) {
            method.setEntity(new UrlEncodedFormEntity(params));

        }

        HttpResponse response = client.execute(method);

        InputStream inputStream = response.getEntity().getContent();
        String result = convertInputStreamToString(inputStream);

        return result;
    }
    catch (ClientProtocolException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

这是请求代码

                                ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
                                params.add(new BasicNameValuePair("region","1"));
                                params.add(new BasicNameValuePair("area","1"));
                                params.add(new BasicNameValuePair("sector","1"));
                                params.add(new BasicNameValuePair("address",edtReqAddres.getText().toString()));
                                params.add(new BasicNameValuePair("mobile",edtMobileNumber.getText().toString()));

                                params.add(new BasicNameValuePair("username","test"));
                                params.add(new BasicNameValuePair("message", edtSubject.getText().toString()));
                                params.add(new BasicNameValuePair("compid","0"));
                                params.add(new BasicNameValuePair("geo","1"));


                                text = webservice.readUrl("http://192.168.1.102:81/api/products", params);

而且这也是我的结果 :(

  

{&#34;消息&#34;:&#34;未找到与请求URI匹配的HTTP资源&#39; http://192.168.1.102:81/api/products&#39;。&#34;}

这是我的WebApi(DotNet)

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    public string GetProductById(int region, int area, int sector, string address, string mobile, string username, string message, int compid, string geo)
    {
      fddService.mobService service=new mobService();
      return service.NewMessage(region, area, sector, address, mobile, "", message, compid, "");
    }

2 个答案:

答案 0 :(得分:2)

如果在Visual Studio中使用ASP.NET WebAPI,则可以添加新的Web API Controller Class(v2.1),然后您将拥有以下默认代码:

public class ProductsController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
}

然后,假设您有一个DTO类,例如产品,您可以按以下方式自定义Web API:

        // POST: api/Products
        [ResponseType(typeof(Product))]
        public async Task<IHttpActionResult> PostProduct(Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Products.Add(product);
            await db.SaveChangesAsync();

            return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
        }

您可以在Learn About ASP.NET Web API

找到更多信息

答案 1 :(得分:0)

所以最后我得到了答案 在客户端您应该将此行添加到您的代码中以设置defult内容类型

httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");

后端服务器(WebApi)上应创建 ModelView 以发送参数,并在输入参数的开头添加[FromBody],如下所示< / p>

public string postreq([FromBody] RequestViewModel model)
{
    fddService.mobService service = new mobService();
    if (model.geo == "1")
        return service.NewMessage(Convert.ToInt32(model.region), Convert.ToInt32(model.area),
            Convert.ToInt32(model.sector), model.address, model.mobile, "", model.message, Convert.ToInt32(model.compid), "");
    else
        return service.NewMessage(Convert.ToInt32(model.region), Convert.ToInt32(model.area),
            Convert.ToInt32(model.sector), model.address, model.mobile, "", model.message, Convert.ToInt32(model.compid), model.geo);
}
public class RequestViewModel
{
    public string region { get; set; }
    public string area { get; set; }
    public string sector { get; set; }
    public string address { get; set; }
    public string mobile { get; set; }
    public string username { get; set; }
    public string message { get; set; }
    public string compid { get; set; }
    public string geo { get; set; }
}

如果你有{"Message":"An error has occurred."}

  

确保您的Android客户端正确地使用正确的POST代码传递参数。

谢谢:Earthling POST data from Android to Web API returns 404