2011-06-30 6 views
10

estoy usando el siguiente código para hacer una llamada httpPost pero me está devolviendo 400 solicitud incorrecta cuando intento dar los siguientes parámetros en "cliente de descanso simple" en la extensión de Chrome funciona bien cualquiera me guía qué error estoy haciendo aquí ?cómo hacer que httpPost llame con el cuerpo json codificado?

simple resto de clientes que formuló la siguiente:

URL: http://jon2012.com/api/register Método: Enviar encabezados: No hay encabezados, ya que no se requieren datos : { "e-mail": "[email protected]", "nombre apellido": "Nombre"} enter image description here

Código 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"); 
     } 

cualquier ayuda appriciated

+0

Es su patrón de datos JSON es igual que el servicio requerido? –

Respuesta

21

Estaba cometiendo un error común. La secuencia del objeto json era incorrecta. Por ejemplo, yo estaba enviando al igual que nombre apellido, email..etc..where secuencia correcta como estaba correo electrónico, First_Name

mi código

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; 
+22

El orden en el que agrega sus parámetros no debe ser absolutamente NINGUNA diferencia. El servidor web que recibe los parámetros no debe importar en qué orden están los parámetros, solo que los parámetros están anidados correctamente y las claves están definidas correctamente – jamesc

+16

No estoy seguro de cómo esta es la respuesta correcta ... y ha sido votado por cuatro gente. El orden de los params JSON definitivamente no importa. –

0

Aquí está mi código para llamar a los servicios de descanso con HTTP POST y JSON:

(Tenga en cuenta que estoy usando AndroidHttpClient, que es básicamente un DefaultHttpClient con algunos atributos predefinidos, y el proyecto GSON de Google para JSON de clasificación)

clase para la comunicación de manipulación:

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

Uso:

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

Espero que esto ayude.

+0

Quiero enviar dos parámetros de correo electrónico y nombre ¿podría indicarme dónde usarlos? – UMAR

+0

¿Qué es Gson? y qué es Somecontent realmente esto es confuso parte – UMAR

+0

SomeContent es un poco de contenido :) Una clase personalizada que tiene los campos que contienen los datos que desea enviar. Gson se usa para ponerlo en json, googlearlo, es bastante útil y fácil de usar que la lib de json predeterminada en el sdk de Android. –

Cuestiones relacionadas