背景:做一个项目的接口对接,用Getman\postman等接口调试工具都是可以的。用程序运行就报415.

原因:根据接口所传参数的不同,post请求的Content-type有四种:

application/x-www-form-urlencoded(默认)

application/xml

application/json

multipart/form-data

我所对接的接口所传的参数是json格式的,代码中没有设置请求头header的Content-Type,默认是application/x-www-form-urlencoded。

        URIBuilder uriBuilder = new URIBuilder(url);
        //创建一个http post请求
        HttpPost httpPost = new HttpPost(uriBuilder.build());
        //设置请求头header
        httpPost.setHeader("Content-Type","application/json");
        //设置请求数据
        httpPost.setEntity(new StringEntity(strJson,"utf-8"));

改动完成以后,接口请求成功。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐