gpt4 book ai didi

android - 为 Rest 客户端设置 Json 内容类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:24:39 26 4
gpt4 key购买 nike

我正在使用 loopj 的 AsyncHttpClient for Android,这样我就可以与我创建的 Restful Web 应用程序进行交互。我已经使用 Postman 测试了 POST 请求,它工作正常。

但是,在 Android 中,我正在努力执行发布请求,因为内容类型始终设置为文本/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);
}

但是我仍然收到相同的消息,这真的很令人沮丧,而且我多年来一直在努力解决这个问题!如果有人对如何设置内容类型有任何想法 - 将不胜感激,谢谢!

最佳答案

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
}
});

关于android - 为 Rest 客户端设置 Json 内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26062084/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com