【问题标题】:Android Cannot POST /api responseAndroid 无法发布 /api 响应
【发布时间】:2015-05-30 18:45:18
【问题描述】:

我正在尝试在 REST 后端执行 HTTP 发布请求。后端的 URL 使用 SSL,因此我还添加了必要的代码来处理它。但我得到了以下回复:

无法发布 /api

这是我的代码:

protected String doInBackground(String... args) {
                try {

                HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
                DefaultHttpClient client = new DefaultHttpClient();
                SchemeRegistry registry = new SchemeRegistry();
                SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
                socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
                registry.register(new Scheme("https", socketFactory, 443));
                SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
                DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());



                HttpPost post = new HttpPost("https://test-api.smart-trial.dk/api");
                List <NameValuePair> nvps = new ArrayList <NameValuePair>(2);
                nvps.add(new BasicNameValuePair("path[pathwayId]","5566e151817a62021b1ea809"));
                nvps.add(new BasicNameValuePair("formData[firstname]","Name"));
                nvps.add(new BasicNameValuePair("formData[lastname]","XXX"));
                nvps.add(new BasicNameValuePair("formData[email]","example@mail.com"));

                 post.addHeader("Referer" ,"https://myurl.com/api");
                 post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


                //DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse response = httpClient.execute(post);
                HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        // get the response content as a string
                        String stringResponse = EntityUtils.toString(entity);

                        Log.d("Response", stringResponse);
                    }

代码有什么问题吗?或者至少为什么我会得到这样的回应。

编辑

我对参数也有一些规则。

“帖子应该用x-www-form-urlencoded body参数完成”
我认为通过使用 x-www-form-urlencoded 的post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));,我或多或少地超越了这一点。

参数:

  1. pathwayId(应该位于路径中)
  2. 名字(应该位于formData中)
  3. 姓氏(应该位于formData中)
  4. email(应该位于formData中)
  5. Referer(应位于 Header 中)

【问题讨论】:

标签: android http-post


【解决方案1】:

听起来您的服务器未配置为允许对该 URL 的 POST 请求。但是您需要一种方法来验证这一点。

如果您的浏览器还没有 REST 测试插件,请找到一个允许您输入 POST 请求数据的插件,下载并安装它。

然后在浏览器插件中复制POST数据,提交请求并查看服务器的响应。

至少这应该可以帮助您确定问题是在应用程序中还是在服务器中。

【讨论】:

    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2019-07-27
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2015-08-13
    相关资源
    最近更新 更多