¿Cómo publicar datos en un Webservice usando JSON?

Tengo que enviar los siguientes datos a webservice en URl

El formato de los datos a enviar es:

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

Donde el email , username y pwd es la clave y tiene la cadena de valor correspondiente obtenida a través de la cadena edittext. Estoy publicando estos datos en un clic del botón.

No estoy recibiendo ninguna respuesta bcoz He intentado contratar comprobar esto con mi co desarrollador en su iphone iphone mismo app versión iphone como el nombre de usuario y la contraseña no es válida se dice por el servidor.

Mi clase de Signup.java es:

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

Por favor, ayúdame soy un novato en JSON y el análisis en Android.Thanx.

Aquí está 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); 

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

 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 el permiso de android.permission.INTERNET

Los paréntesis de bloque denotan una matriz JSON, por lo que sólo es necesario que envuelva 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); 

Coloca el array en entidad.

Importante: no debe realizar tareas de larga duración (por ejemplo, de red) en el subproceso principal. Utilice AsyncTask para realizar correctamente las tareas de larga ejecución en segundo plano y, a continuación, actualizar la interfaz de usuario.

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

A continuación, parece que el servidor espera un JSONArray con sólo un elemento, por lo que tendrá que crear un JSONArray, algo así:

 JSONArray jsonArray=new JSONArray(); jsonArray.put(json); //your current json StringEntity entity=new StringEntity("new_member="+jsonArray); 
  • Retrofit: Se esperaba BEGIN_OBJECT pero era BEGIN_ARRAY
  • JSONArray a HashMap
  • JSON a clase Java
  • No puedo trabajar con Jackson
  • IOException e es nulo
  • Mensaje de error 'java.net.SocketException: socket failed: EACCES (Permiso denegado)'
  • Error json de Android com.google.gson.JsonSyntaxException: java.lang.IllegalStateException
  • Pasando el objeto JSON en la URL del servicio Web RESTFUL en Android?
  • JSON Parsing funciona en Android 4.0 pero no en Android <4.0
  • Conversión de la matriz JSON a POJO utilizando el mapeador de objetos jackson
  • Bucle JSONArray de Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.