如何使用JSON向Webservice发布数据?

9

我需要将以下数据发送到URl的webservice:

要发送的数据格式为:

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

其中emailusernamepwd是关键字,通过编辑文本字符串获取相应的值字符串。我在点击按钮时发布此数据。

我没有得到任何响应,因为我已经尝试与我的合作者进行反向检查,在他的iPhone上使用相同的应用程序和iPhone版本,服务器说用户名和密码无效。

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

    }
            );

请帮助我,我是一个在Android中JSON解析的新手。谢谢。

4个回答

12

这是一个例子

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

请查看此博客以获取完整信息:http://simpleprogrammer.com/2011/06/04/oauth-and-rest-in-android-part-2/


谢谢您的回复,请告诉我如何传递new_member=,因为我正在将其附加到URL中,但实际提供的URL是http://www.fourerr.com/ws/signup。我应该将newmember作为JSON对象吗?请帮助我。 - Gaurav Chawla
这个 new_member 值是什么?尝试像示例中传递令牌一样传递。 - Pratik
2
我建议使用 StringEntity entity = new StringEntity(paramInput.toString(), HTTP.UTF_8); 而不是 StringEntity entity = new StringEntity(data.toString()); - 在我的情况下,这解决了在json字符串中编码西里尔字符的问题。 - Prizoff
对于编码需要使用HTTP.UTF_8。 - Pratik

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

请不要忘记指定 android.permission.INTERNET 权限。

2
块括号表示JSON数组,因此您只需将json对象包装在JSONArray中即可。
JSONArray array = new JSONArray();
JSONObject json = new JSONObject();
json.put("email", a);
json.put("username", b);
json.put("pwd",c); 
array.put(json);

数组放入实体中。

重要提示:不应在主线程上执行长时间运行(例如网络)任务。请使用AsyncTask来正确地在后台执行长时间运行的任务,然后更新UI。


谢谢回复,请告诉我如何传递new_member=,因为我正在将其附加到URL中,但实际提供的URL是http://www.fourerr.com/ws/signup。我应该将newmember作为JSON对象吗?请帮助我。 - Gaurav Chawla

1
首先,您需要将从EditTexts获取Stringscode放入onClick()方法中。
然后,看起来服务器期望一个只有一个项目的JSONArray,因此您需要创建一个JSONArray,类似于这样:
JSONArray jsonArray=new JSONArray();
jsonArray.put(json); //your current json
StringEntity entity=new StringEntity("new_member="+jsonArray);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接