简体   繁体   中英

Android - How to post a json string to a web service which accepts parameters?

I have a web service which accepts 2 parameters to save json: fileName and a json string. I need to post a json string to this web service. I have tried the method outlined in How to send a JSON object over Request with Android? but it doesn't seem to work. Any pointers??

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

  }

The fileName and json don't go in the httpParams. They go in the Entity. You should use an HttpEntity, most likely a http://developer.android.com/reference/org/apache/http/client/entity/UrlEncodedFormEntity.html with 2 BasicNameValuePair, one for the fileName, one for the json.

This is my custom WebServiceHelper class:

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;


        }

    }

then make its object in your class and do your thing :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM