我正在使用以下代码进行httpPost调用,但它返回了400个错误请求 当我尝试在chrome扩展中的“简单休息客户端”中提供以下参数时,它可以正常工作,指导我在这里做了什么错误?
简单休息客户端我输入以下内容:
网址:http://jon2012.com/api/register 方法:POST 标题:没有标题,因为它们不是必需的 数据:{“email”:“test@example.com”,“first_name”:“姓名”}
Android代码:
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try{
HttpPost post = new HttpPost(url);
json.put("email", email);
json.put("first_name", name);
StringEntity se = new StringEntity( "JSON: " + json.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
/*if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
*/
int statusCode = response.getStatusLine().getStatusCode();
}
catch(Exception e){
e.printStackTrace();
// createDialog("Error", "Cannot Estabilish Connection");
}
任何帮助都是适当的
答案 0 :(得分:21)
我犯了一个常见的错误,json对象的序列错了。 例如,我发送它就像 first_name,email..etc..where正确的序列是email,first_name
我的代码
boolean result = false;
HttpClient hc = new DefaultHttpClient();
String message;
HttpPost p = new HttpPost(url);
JSONObject object = new JSONObject();
try {
object.put("updates", updates);
object.put("mobile", mobile);
object.put("last_name", lastname);
object.put("first_name", firstname);
object.put("email", email);
} catch (Exception ex) {
}
try {
message = object.toString();
p.setEntity(new StringEntity(message, "UTF8"));
p.setHeader("Content-type", "application/json");
HttpResponse resp = hc.execute(p);
if (resp != null) {
if (resp.getStatusLine().getStatusCode() == 204)
result = true;
}
Log.d("Status line", "" + resp.getStatusLine().getStatusCode());
} catch (Exception e) {
e.printStackTrace();
}
return result;
答案 1 :(得分:0)
这是我用Http POST和JSON调用休息服务的代码:
(请注意,我使用的是AndroidHttpClient,它基本上是带有一些预设属性的DefaultHttpClient,以及Google用于JSON编组的GSON项目)
处理沟通的类别:
public class NetworkComm extends AsyncTask<String, Integer, String> {
// Log tag
private static final String TAG = "NetworkComm";
private AndroidHttpClient hc;
private HttpContext localContext;
private TaskResponseListener listener;
private int reqType;
private String message;
private String url;
private Object extra;
public NetworkComm(AndroidHttpClient hc, HttpContext localContext, TaskResponseListener listener,
int reqType, String message, String url, Object extra){
super();
this.hc = hc;
this.localContext = localContext;
this.listener = listener;
this.reqType = reqType;
this.message = message;
this.url = url;
this.extra = extra;
}
public AndroidHttpClient getHc() {
return hc;
}
public void setHc(AndroidHttpClient hc) {
this.hc = hc;
}
public HttpContext getLocalContext() {
return localContext;
}
public void setLocalContext(HttpContext localContext) {
this.localContext = localContext;
}
public void start(){
this.execute(message);
}
protected void onPreExecute() {
//Don't do anything here
}
protected String doInBackground(String... req) {
Log.d(TAG, "Message to send: "+req[0]);
HttpPost p = new HttpPost(url);
try{
p.setEntity(new StringEntity(req[0], "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
String response = "";
try{
HttpResponse resp = hc.execute(p, localContext);
InputStream is = resp.getEntity().getContent();
response = convertStreamToString(is);
Log.d("Response", "Response is " + response);
Log.d("Status line", ""+resp.getStatusLine().getStatusCode());
} catch (Exception e){
e.printStackTrace();
}
return response;
}
protected void onProgressUpdate(Integer... progress) {
// dont handle this yet
}
@Override
protected void onCancelled() {
super.onCancelled();
}
protected void onPostExecute(String result) {
Log.d("task", "task finished");
listener.onTaskResponse(reqType, result, extra);
}
public interface TaskResponseListener{
public void onTaskResponse(int type, String response, Object extra);
}
private String convertStreamToString(InputStream is) throws IOException {
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
用法:
Gson g = new Gson();
SomeContent content = new SomeContent("Stuff", 4);
String message = g.toJson(content);
NetworkComm task = new NetworkComm(hc, localContext, listener, 0, message, url, "");
task.start();
希望这会有所帮助。