【问题标题】:Android - How to post a json string to a web service which accepts parameters?Android - 如何将 json 字符串发布到接受参数的 Web 服务?
【发布时间】:2012-09-06 15:42:42
【问题描述】:

我有一个网络服务,它接受 2 个参数来保存 json:文件名和 json 字符串。我需要向这个 Web 服务发布一个 json 字符串。我已经尝试过How to send a JSON object over Request with Android? 中概述的方法,但它似乎不起作用。有什么指点吗??

public void postDataToServer(String url, String jsonStr) throws ClientProtocolException, IOException
  {
      int TIMEOUT_MILLISEC = 10000;  // = 10 seconds
      HttpParams httpParams = new BasicHttpParams();
      HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
      HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
      httpParams.setParameter("fileName","testFile");
      httpParams.setParameter("json",jsonStr);
      HttpClient client = new DefaultHttpClient(httpParams);

      HttpPost request = new HttpPost(url);
      request.setEntity(new ByteArrayEntity(
          jsonStr.getBytes("UTF8")));
      HttpResponse response = client.execute(request);

  }

【问题讨论】:

  • “它似乎不起作用”。这又意味着什么?
  • 当我尝试从服务器检索 json 时,出现“未找到 Json 文件”错误。

标签: android json web-services


【解决方案1】:

文件名和 json 不在 httpParams 中。他们进入实体。您应该使用 HttpEntity,很可能是 http://developer.android.com/reference/org/apache/http/client/entity/UrlEncodedFormEntity.html 有 2 个 BasicNameValuePair,一个用于文件名,一个用于 json。

【讨论】:

【解决方案2】:

这是我的自定义 WebServiceHelper 类:

public class WebserviceHelper { 


    private Context c;
    public String bytesSent;
    private String tempRespo;

    public String hitWeb(Context c,String url, String json){

        this.c=c;
        try {
            tempRespo = new hitAsync(url,json).execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return tempRespo;
    }

    class hitAsync extends AsyncTask<Void, Void , String>
    {


        private String url;
        private String json;
        ProgressDialog pDialog;

        public hitAsync(String url, String json) {
            // TODO Auto-generated constructor stub

            this.url = url;
            this.json = json;
        }

        @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            pDialog.dismiss();
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            pDialog = new ProgressDialog(c);
            pDialog.setMessage("Please Wait...");
            pDialog.show();
            pDialog.setCancelable(false);

        }

        @Override
        protected String doInBackground(Void... params) {
            // TODO Auto-generated method stub

              HttpClient client = new DefaultHttpClient();
              HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
              HttpResponse response;

              try{
                  HttpPost post = new HttpPost(url);

                  StringEntity se = new StringEntity( json);  
                  se.setContentType(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

                      BufferedInputStream bis = new BufferedInputStream(in);
                    ByteArrayBuffer baf = new ByteArrayBuffer(20);

                    int current = 0;
                    while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                    }

                     bytesSent = new String(baf.toByteArray());

                  }
              }
              catch(Exception e){
                  e.printStackTrace();
              }
            return bytesSent;


        }

    }

然后在你的类中创建它的对象并做你的事情:

 ws = new WebserviceHelper();
    String respo = ws.hitWeb(// ur class context", "// url","//json string");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 2012-05-21
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 2016-08-02
    • 1970-01-01
    相关资源
    最近更新 更多