9

I have to send the following data to webservice at URl

The format of data to be send is:

new_member=[{"email":"himanshu@avigma.com","username":"himanshu01","pwd":"himanshu01"}]

where email,username and pwd is the key and has corresponding value string fetched through edittext string. I am posting this data on click of button.

I am not getting any response bcoz i have tried to counter check this with my co developer in his iphone same app iphone version as the username and password is not valid is said by server.

My Signup.java class is:

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

    }
            );

Please assist me i am a newbie in JSON and parsing in Android.Thanx.

Gaurav Chawla
  • 1,847
  • 3
  • 18
  • 26

4 Answers4

12

here is the example

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

see the complete information from this blog http://simpleprogrammer.com/2011/06/04/oauth-and-rest-in-android-part-2/

Pratik
  • 30,639
  • 18
  • 84
  • 159
  • Thanx for the reply please tell me how i pass new_member= as i am appending in the url but the actual provided url is http://www.fourerr.com/ws/signup Should i take newmember as json object.?? Please assist me.. – Gaurav Chawla Dec 15 '11 at 12:52
  • what this new_member value? try to pass like token was pass in example – Pratik Dec 15 '11 at 12:55
  • 2
    I would recommend using not **StringEntity entity = new StringEntity(data.toString());** but **StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8);** - In my case this solved the problem with encoding cyrillic characters in json-string. – Prizoff Jun 05 '12 at 11:23
  • for encoding it's required HTTP.UTF_8 – Pratik Jun 05 '12 at 12:40
4
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);

nameValuePairs.add(new BasicNameValuePair("email", "himanshu@avigma.com"));  
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();
                }

Dont forgot to specify android.permission.INTERNET permission

Gaurav Chawla
  • 1,847
  • 3
  • 18
  • 26
KK_07k11A0585
  • 2,381
  • 3
  • 26
  • 33
2

The block parentheses denote a JSON array, so you just need to wrap your json object in a JSONArray.

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

The put array into entity.

Important: you should not perform long-running (e.g. network) tasks on main thread. Use AsyncTask to properly perform long-running tasks in the background and then update UI.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154
  • Thanx for the reply please tell me how i pass new_member= as i am appending in the url but the actual provided url is http://www.fourerr.com/ws/signup Should i take newmember as json object.?? Please assist me.. – Gaurav Chawla Dec 15 '11 at 12:51
1

First of all you'll need to put the code that gets the Strings from the EditTexts inside the onClick() method.

Then it looks like the server expects a JSONArray with just one item, so you'll need to create a JSONArray, something like this :

JSONArray jsonArray=new JSONArray();
jsonArray.put(json); //your current json
StringEntity entity=new StringEntity("new_member="+jsonArray);
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84