简体   繁体   English

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

[英]Sending JSON data and Image to Server

I'm not sure if I'm taking the correct course in trying to achieve my objective. 我不确定我是否在尝试正确的方法来实现自己的目标。

I'm trying to send both JSON data and an image to a server. 我正在尝试将JSON数据和图像发送到服务器。 When the user clicks on a button the async call activates, gathers the JSON container that has the data and gets the image path. 当用户单击按钮时,异步调用将激活,收集具有数据的JSON容器并获取图像路径。 Here's is what I have so far: 这是我到目前为止的内容:

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

Now the problem is that I can send either or, not both. 现在的问题是我可以发送一个,也可以不发送。 Is there a way to append the image data to the setEntity so that its aggregates both of them? 有没有一种方法可以将图像数据附加到setEntity上,以便将它们聚合在一起? Thank ye. 谢谢你们

Add both parameters to MultipartEntity instead of calling setEntity two times because second call of setEntity method will override first method call settings do it as: 将两个参数都添加到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