【问题标题】:How to post data to a Webservice using JSON?如何使用 JSON 将数据发布到 Web 服务?
【发布时间】:2012-06-05 20:41:00
【问题描述】:

我必须将以下数据发送到 URl 的 web 服务

要发送的数据格式为:

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

其中email,usernamepwd是key,通过edittext字符串获取对应的value字符串。我在单击按钮时发布此数据。

我没有得到任何回复,因为我试图与我的合作开发人员在他的 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"); 
                } 
        }

    }
            );

请帮助我,我是 JSON 和 Android.Thanx 解析的新手。

【问题讨论】:

    标签: android json


    【解决方案1】:

    这里是例子

    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 是 fourerr.com/ws/signup 我应该将 newmember 作为 json 对象吗??请帮助我..
    • 这个 new_member 值是多少?尝试像在示例中传递的令牌一样传递
    • 我建议不要使用 StringEntity entity = new StringEntity(data.toString()); 而是 StringEntity entity = new StringEntity(paramInput.toString(), HTTP .UTF_8); - 就我而言,这解决了在 json-string 中编码西里尔字符的问题。
    • 编码需要HTTP.UTF_8
    【解决方案2】:
    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权限

    【讨论】:

      【解决方案3】:

      块括号表示一个 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);
      

      array 放入实体中。

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

      【讨论】:

      • 感谢您的回复,请告诉我如何通过 new_member= 因为我在 url 中附加,但实际提供的 url 是 fourerr.com/ws/signup 我应该将 newmember 作为 json 对象吗??请帮助我..
      【解决方案4】:

      首先,您需要将从EditTexts 获取Stringscode 放入onClick() 方法中。

      然后看起来服务器期望 JSONArray 只有一个项目,所以您需要创建一个 JSONArray,如下所示:

      JSONArray jsonArray=new JSONArray();
      jsonArray.put(json); //your current json
      StringEntity entity=new StringEntity("new_member="+jsonArray);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 2011-11-12
        • 1970-01-01
        • 2018-04-27
        相关资源
        最近更新 更多