2011-12-15 18 views
8

tengo que enviar los siguientes datos para servicio web en la URL¿Cómo publicar datos a un servicio web utilizando JSON?

El formato de los datos que se van a enviar es:

new_member=[{"email":"[email protected]","username":"himanshu01","pwd":"himanshu01"}] 

donde email, username y pwd es la clave y tiene cadena de valor correspondiente descabellada a través EditarTexto cuerda. Estoy publicando estos datos al hacer clic en el botón.

No estoy recibiendo ninguna respuesta bcoz he tratado de contrarrestar comprobar esto con mi co desarrollador en su iphone misma versión de la aplicación iPhone como el nombre de usuario y la contraseña no es válido que se dice por el servidor.

Mi clase es Signup.java:

Button b1=(Button)findViewById(R.id.button1); 
    b1.setOnClickListener(new OnClickListener() 
    { 
     EditText e=(EditText)findViewById(R.id.editText1); 
     String a=e.getText().toString(); 
     EditText e1=(EditText)findViewById(R.id.editText1); 
     String b=e1.getText().toString(); 
     EditText e2=(EditText)findViewById(R.id.editText1); 
     String c=e2.getText().toString(); 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      HttpClient client = new DefaultHttpClient(); 
       HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit 
       HttpResponse response; 
       JSONObject json = new JSONObject(); 
       try{ 
        HttpPost post = new HttpPost("URL"); 
        //System.out.println(post); 
        json.put("email", a); 
        json.put("username", b); 
        json.put("pwd",c); 
        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 
//System.out.println(response); 
       } 
       } 
       catch(Exception e){ 
        e.printStackTrace(); 
        System.out.println(e.toString()); 
        //createDialog("Error", "Cannot Estabilish Connection"); 
       } 
     } 

    } 
      ); 

favor me ayude soy un novato en JSON y analizar en Android.Thanx.

Respuesta

10

aquí es el ejemplo

HttpClient httpClient = new DefaultHttpClient(); 
HttpPost httpPost = new HttpPost(
    "https://api.dailymile.com/entries.json?oauth_token=" 
    + token); 

httpPost.setHeader("content-type", "application/json"); 
JSONObject data = new JSONObject(); 

data.put("message", dailyMilePost.getMessage()); 
JSONObject workoutData = new JSONObject(); 
data.put("workout", workoutData); 
workoutData.put("activity_type", dailyMilePost.getActivityType()); 
workoutData.put("completed_at", dailyMilePost.getCompletedAt()); 
JSONObject distanceData = new JSONObject(); 
workoutData.put("distance", distanceData); 
distanceData.put("value", dailyMilePost.getDistanceValue()); 
distanceData.put("units", dailyMilePost.getDistanceUnits()); 
workoutData.put("duration", dailyMilePost.getDurationInSeconds()); 
workoutData.put("title", dailyMilePost.getTitle()); 
workoutData.put("felt", dailyMilePost.getFelt()); 

StringEntity entity = new StringEntity(data.toString(), HTTP.UTF_8); 
httpPost.setEntity(entity); 

HttpResponse response = httpClient.execute(httpPost); 

vea la información completa de este blog http://simpleprogrammer.com/2011/06/04/oauth-and-rest-in-android-part-2/

+0

Gracias por la respuesta, por favor díganme cómo paso a new_member = ya que estoy anexando en la url, pero la url proporcionada es http://www.fourerr.com/ws/signup ¿Debo tomar newmember como json? objeto.?? Por favor me ayude .. –

+0

lo que este valor new_member? Tratar de pasar el token como se pasó en el ejemplo – Pratik

+2

Yo recomendaría usar no ** StringEntity entity = new StringEntity (data.toString()); ** pero ** StringEntity entity = new StringEntity (paramInput.toString(), HTTP.UTF_8); ** - En mi caso, esto resolvió el problema con la codificación de caracteres cirílicos en json-string. – Prizoff

2

Los paréntesis denotan un bloque matriz JSON, por lo que sólo hay que envolver su objeto JSON en un JSONArray.

JSONArray array = new JSONArray(); 
JSONObject json = new JSONObject(); 
json.put("email", a); 
json.put("username", b); 
json.put("pwd",c); 
array.put(json); 

Poner array en la entidad.

Importante: no debe realizar tareas de larga ejecución (por ejemplo, de red) en el hilo principal. Utilice AsyncTask para llevar a cabo correctamente las tareas a largo ejecutan en segundo plano y luego actualizar la interfaz de usuario.

+0

Gracias por la respuesta, dígame cómo paso a new_member = como anexo en la url, pero la url proporcionada es http://www.fourerr.com/ws/signup ¿Debería tomar newmember como objeto json? Por favor ayúdenme ... –

1

En primer lugar tendrá que poner el code que obtiene el Strings del EditTexts dentro del método onClick().

entonces parece que el servidor espera una JSONArray con un solo tema, por lo que necesita para crear un JSONArray, algo como esto:

JSONArray jsonArray=new JSONArray(); 
jsonArray.put(json); //your current json 
StringEntity entity=new StringEntity("new_member="+jsonArray); 
4
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); 

nameValuePairs.add(new BasicNameValuePair("email", "[email protected]")); 
nameValuePairs.add(new BasicNameValuePair("username", "himanshu01")); 
nameValuePairs.add(new BasicNameValuePair("pwd", "himanshu01")); 

// You have to add your parameters as nameValuePairs 

String res = ""; 
       try 
       { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("URL"); 

          // Add your data 

          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
          HttpResponse response = httpclient.execute(httppost); 
          res = EntityUtils.toString(response.getEntity()); 
          JSONTokener t = new JSONTokener(res); 
          JSONArray a = new JSONArray(t); 
          JSONObject o = a.getJSONObject(0); 
          String sc = o.getString("success"); 
          if(sc.equals("1")) 
          { 
           // posted successfully 
          } 
else 
{ 
// error occurred 
} 
       } 
       catch (Exception e) 
       { 

        e.printStackTrace(); 
       } 

No se olvidó de especificar android.permission.INTERNET permiso

Cuestiones relacionadas