繁体   English   中英

将JSON数据和图像发送到服务器

[英]Sending JSON data and Image to Server

我不确定我是否在尝试正确的方法来实现自己的目标。

我正在尝试将JSON数据和图像发送到服务器。 当用户单击按钮时,异步调用将激活,收集具有数据的JSON容器并获取图像路径。 这是我到目前为止的内容:

protected String doInBackground(String... data) {
            gatherEditTextStringValue();

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);

            try {
                ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();
                postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSONMainContainer)));
                httppost.setEntity(new UrlEncodedFormEntity(postVars));

                if (questionTitleImageUri != null) {
                    questionTitleImageFile = new File(getRealPathFromURI(questionTitleImageUri));
                    FileBody bin1 = new FileBody(questionTitleImageFile);
                    MultipartEntity reqEntity = new MultipartEntity();
                    reqEntity.addPart("uploadedfile1", bin1);
                    httppost.setEntity(reqEntity);
                }

            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            try {
                HttpResponse response = httpclient.execute(httppost);
                responseBody = EntityUtils.toString(response.getEntity());
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return responseBody;
        }

现在的问题是我可以发送一个,也可以不发送。 有没有一种方法可以将图像数据附加到setEntity上,以便将它们聚合在一起? 谢谢你们

将两个参数都添加到MultipartEntity而不是两次调用setEntity ,因为第二次调用setEntity方法将覆盖第一个方法的调用设置,方法如下:

MultipartEntity reqEntity = new MultipartEntity();
// add file
reqEntity.addPart("uploadedfile1", bin1);
// add JSON String 
reqEntity.addPart("JSON", new StringBody(String.valueOf(JSONMainContainer)));
httppost.setEntity(reqEntity);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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