将一个JSON对象从android传递给servlet

时间:2014-07-10 06:14:14

标签: java android json servlets

我使用下面的代码从我的Android应用程序上传文件到服务器,它的工作正常。现在我想将一个jsonobject传递给servlet,我试过像

这样的方式
    mpEntity.addPart("param",new StringBody(details.toString(),"text/plain",
                    Charset.forName("UTF-8")));

这里的细节是一个JSON对象,但它不起作用,所以请帮我解决这个问题。

这是我的代码(在android中)用于文件上传。

           private class AsyncCaller extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected Void doInBackground(Void... params) {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(
                CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        JSONObject obj=new JSONObject();
        try {
            obj.put("m1", "adad");

        obj.put("m2", "adadad");
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        HttpPost httppost = new HttpPost(
                "http://172.20.56.229:8084/AndroidTesting/UploadServlet");

        File file = new File("/sdcard/CEA.txt");

        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFe = new FileBody(file, "image/jpeg");
        mpEntity.addPart("userfile", cbFe);
        httppost.setEntity(mpEntity);
        System.out
                .println("executing request " + httppost.getRequestLine());
        HttpResponse response;
        try {
            response = httpclient.execute(httppost);

            HttpEntity resEntity = response.getEntity();
            httpclient.getConnectionManager().shutdown();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

0 个答案:

没有答案