【问题标题】:Setting Json content-type for Rest client为 Rest 客户端设置 Json 内容类型
【发布时间】:2014-11-21 14:43:56
【问题描述】:

我正在为 Android 使用 loopj 的 AsyncHttpClient,以便我可以与我创建的安静的 Web 应用程序进行交互。我已经使用 Postman 测试了一个 POST 请求,它工作正常。

但是,在 Android 中,我很难进行发布请求,因为内容类型始终设置为 text/html..

    RequestParams params = new RequestParams();
    params.setUseJsonStreamer(true);
    params.put("email", "android@tester.com");
    StringEntity se = null;
    try {
        se = new StringEntity(params.toString());
        se.setContentType("application/json");
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    Header headers[] = {};
    if(getActivity() != null){
    RestClient.postWithContentType(getActivity(), "contacts", se, "application/json", new AsyncHttpResponseHandler() {
        //onSuccess and onFailure methods ommitted

    });

它一直失败,我在 logcat 中收到此消息: 传递的 contentType 将被忽略,因为 HttpEntity 设置了内容类型。

所以,我试图改变这一点,

 public static void postWithContentType(Context context,String url,StringEntity s,String contentType, AsyncHttpResponseHandler responseHandler){
      s.setContentType("application/json");
      client.post(context, getAbsoluteUrl(url), s, contentType, responseHandler); 
  }

但是我仍然收到相同的消息,这真的很令人沮丧,而且我已经尝试了很长时间了! 如果有人对如何设置内容类型有任何想法 - 将不胜感激,谢谢!

【问题讨论】:

  • RestClient 到底是什么?你什么都没说。也许它的实现搞砸了?

标签: android json rest post content-type


【解决方案1】:
RequestParams requestParams = new RequestParams();
asyncHttpClient.addHeader("Accept", "text/json");
asyncHttpClient.addHeader("content-type", "application/json");
asyncHttpClient.post(context, getAbsoluteUrl(url), requestParams, new AsyncHttpResponseHandler() {
   @Override
   public void onSuccess(int statusCode, String content) {
       super.onSuccess(content
       // Ur logic
   }

   @Override
   public void onFailure(Throwable error, String content) {
       super.onFailure(error, content);
       // Ur logic
   }
});

【讨论】:

    【解决方案2】:

    我有同样的问题。

    我不明白是什么影响了它,因为它在几天前确实有效。我只是再次手动添加标题,它可以工作。

    只需在您的RestClient.postWithContentType(...) 代码上方添加RestClient.addHeader("Content-Type", "application/json");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-16
      • 2012-10-10
      • 2013-04-04
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-06-16
      • 1970-01-01
      相关资源
      最近更新 更多