【发布时间】:2014-10-29 22:55:55
【问题描述】:
我正在尝试将 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 响应。那么我的代码有什么问题?
【问题讨论】:
-
@Abdellah 我已经有了。对我帮助不大
-
你是怎么开发东西服务器端的?
-
不,我刚拿到这个 api,我正在处理它,curl 请求工作正常,你检查了吗?
-
@Abdellah 卷曲工作很好我再次尝试它工作并且我已经解决了问题检查我的新帖子我要写回复。