gpt4 book ai didi

android - 在android中发送JSON请求POST

转载 作者:行者123 更新时间:2023-11-29 20:59:21 25 4
gpt4 key购买 nike

我正在尝试将 json post 请求发送到:http://5.101.97.65:3000/en/api/sessions

发布请求结构:

{user: {email: 'value', password: 'value '} }

响应应该是这样的:

{"success":true Or False,"info":"...","data":{"auth_token":"...."}}

对于这个例子,通常它应该为“成功”键返回真值:

{"user":{"email":"user@example.com","password":"changeme"}}

这是我的代码:

final String myUrl ="http://5.101.97.65:3000/api/sessions";
String result = null;
String params = "{\"user\":{\"email\":\"user@example.com\",\"password\":\"changeme\"}}";
try {
restHandler rh = new restHandler();
result = rh.getResponse(myUrl, 2, params);
JSONObject rs = new JSONObject(result);
if (rs.getBoolean("success"))
return "good";
else
return "baad";
}
catch (Exception e){
e.printStackTrace();
return "baaad";
}

restHandler 类(仅函数 getResponse):

public String getResponse (String url, int method, String params) {
try {
// http client
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

// Checking http request method type
if (method == 2) {
HttpPost httpPost = new HttpPost(url);
if (params != null)
{
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(params, "UTF8"));
}
httpResponse = httpClient.execute(httpPost);

} else if (method == 1) {
// code for httpGet not needed here
}

httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
httpClient = null;
httpEntity = null;
httpResponse = null;


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

我经常遇到的问题是 错误页面的 HTML 代码,甚至不是 json 响应。那么我的代码有什么问题呢?

最佳答案

问题是,当我发送 Post Request 时,总是以 PlainText 的形式发送,所以我更改了这个:

HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

为此:

HttpClient httpClient = new DefaultHttpClient();

然后我添加了:

httpPost.addHeader("Accept", "application/json");

解决响应422 unprocessable entity问题。

最终代码(仅更新部分)

HttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;

// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null)
{
httpPost.setHeader("Content-type", "application/json");
httpPost.addHeader("Accept", "application/json");
httpPost.setEntity(new StringEntity(params));

}

关于android - 在android中发送JSON请求POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642085/

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