2011-12-15 35 views
8

devo inviare i seguenti dati per webservice all'indirizzo URLCome inviare dati a un servizio Web utilizzando JSON?

Il formato dei dati da trasmettere è:

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

dove email, username e pwd è la chiave e ha stringa corrispondente valore recuperati attraverso EditText stringa. Sto postando questi dati cliccando sul pulsante.

Non riesco a ottenere alcuna risposta bcoz ho provato a contrastare questo con il mio co-sviluppatore nella sua versione iphone iphone app stessa come il nome utente e la password non è valida è detto dal server.

La mia classe è 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"); 
       } 
     } 

    } 
      ); 

Si prega di aiutare me Sono un novizio in JSON e l'analisi in Android.Thanx.

risposta

10

Ecco l'esempio

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

vedi le informazioni complete da questo blog http://simpleprogrammer.com/2011/06/04/oauth-and-rest-in-android-part-2/

+0

Grazie per la risposta per favore dimmi come passo new_member = come sto aggiungendo nell'URL ma l'url fornito è http://www.fourerr.com/ws/signup Dovrei prendere newmember come json oggetto.?? Per favore, aiutami .. –

+0

che valore ha questo new_member? provare ad inviare come token è stato superato nell'esempio – Pratik

+2

Si consiglia di utilizzare non ** StringEntity entity = new StringEntity (data.toString()); ** but ** StringEntity entity = new StringEntity (paramInput.toString(), HTTP.UTF_8); ** - Nel mio caso questo ha risolto il problema con la codifica di caratteri cirillici in json-string. – Prizoff

2

Le parentesi dei blocchi indicano un array JSON, quindi è sufficiente avvolgere l'oggetto JSON in 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); 

put array in entità.

Importante: non eseguire attività di lunga durata (ad es. Rete) sul thread principale. Utilizzare AsyncTask per eseguire correttamente attività a esecuzione prolungata in background e quindi aggiornare l'interfaccia utente.

+0

Grazie per la risposta per favore dimmi come passo new_member = come sto aggiungendo nell'URL ma l'url fornito è http://www.fourerr.com/ws/iscrizione Dovrei prendere newmember come json object. ?? Per favore aiutami .. –

1

Prima di tutto è necessario mettere la code che ottiene il Strings dal EditTexts all'interno del metodo onClick().

Poi sembra che il server si aspetta un JSONArray con un solo elemento, quindi avrai bisogno di creare un JSONArray, qualcosa di simile:

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

Non ho dimenticato di specificare permesso android.permission.INTERNET

Problemi correlati