使用 AndroidAsyncHttp 库发送文件

Sending files with AndroidAsyncHttp library

我正在尝试通过 Android Async Http (android-async-http:1.4.9) 库发送文件,我试图在 fiddler 中发出的请求如下所示:

Header:

Content-Type: multipart/form-data; boundary=-------------------------acebdf13572468 User-Agent: Fiddler Host: tehran.plaza.ir Content-Length: 100033 X-Authentication: Rx7Xyu3zU+zoPXItcccSBHnXP73J0DZ62kIWw4EUGD88Y8v3jICHkQZ9XRDUfJz7 Fiddler-Encoding: base64

请求Body:

---------------------------acebdf13572468 Content-Disposition: form-data; name="fieldNameHere"; filename="a.jpg" Content-Type:

image/jpeg

<@INCLUDE C:\Users\ekr\Desktop\a.jpg@> ---------------------------acebdf13572468 Content-Disposition: form-data; name="model"; filename="" Content-Type:application/json

{"id":1} ---------------------------acebdf13572468--

我的错误:

05-03 11:21:21.884 29989-29989/gilertebat.com.scaan E/EKRAMI: {"Message":"An error has occurred.","ExceptionMessage":"Object reference not set to an instance of an object.","ExceptionType":"System.NullReferenceException","StackTrace":"   at System.Web.Http.ApiController.<InvokeActionWithExceptionFilters>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__0.MoveNext()"}

我的代码:

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addBinaryBody("file.jpg", new File(filePaths), ContentType.create("multipart/form-data; boundary=-------------------------acebdf13572468"), new File(filePaths).getName());
        builder.addTextBody("id", propertyID, ContentType.create("application/json"));

        HttpEntity entity = builder.build();


        ScaanRestClient restClient = new ScaanRestClient(getApplicationContext());
        restClient.post("/api-builtin/properties/v1.0/edit/photo/", entity, null);

它是一个 ImageFile(多部分内容类型)和一个 JSONObject(application/json 内容类型)

提前感谢您的帮助

在将图像文件发送到 API 时,将图像文件转换为 Base64,然后通过 API 发送。

link 来自 trinitytuts

试试这个: 使用针对多部分内容类型的 AndroidAsynchttp 库发送 img 文件)和 JSONObject(application/json 内容类型)尝试一下。

  new AsyncTask<String, String, String>() {
                        @Override
                        protected void onPreExecute() {
                            mProgressDialog.show();
                        }

                        @Override
                        protected String doInBackground(String... params) {
                            // something you know that will take a few seconds
                            String serviceBaseUrl = "http://YOUR_URL";
                            String responseId = "";
                            HttpParams httpParams = new BasicHttpParams();
                            ConnManagerParams.setTimeout(httpParams, 10000);
                            HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
                            HttpConnectionParams.setSoTimeout(httpParams, 50000);
                            HttpClient client = new DefaultHttpClient(httpParams);
                            HttpPost post = new HttpPost(serviceBaseUrl);
                            String baseDir = Environment.getExternalStorageDirectory()
                                    .getAbsolutePath();
                            String filePath = baseDir + "/Folder_name/a.jpg";
                            String mFileName = "a.jpg";
                            File file = new File(filePath);
                            FileBody imageFile = null;
                            try {
                                if (file != null) {
                                    imageFile = new FileBody(file);
                                }
                                MultipartEntity reqEntity = new MultipartEntity(
                                        HttpMultipartMode.BROWSER_COMPATIBLE, null,
                                        Charset.forName("UTF-8"));
                                reqEntity.addPart("uid", new StringBody(
                                        uid));
                                if (!mFileName.isEmpty()) {
                                    reqEntity
                                            .addPart("FileName", new StringBody(mFileName));
                                }
                                if (!"".equals(imageFile) && !"null".equals(imageFile)) {
                                    if (imageFile.getFile() != null
                                            && imageFile.getFile().exists()) {
                                        reqEntity.addPart(mFileName, imageFile);
                                    }
                                }
                                post.setEntity(reqEntity);
                                HttpResponse response = client.execute(post);
                                responseId = EntityUtils.toString(response
                                        .getEntity());
                            } catch (Exception e) {
                                System.out.println("Excep" + e);
                                responseId = "false";
                            }
                            return responseId;
                        }

                        @Override
                        protected void onPostExecute(final String result) {
                            mProgressDialog.dismiss();
    // ur stuff
                        }
                    }.execute();

我也请求添加这些库:

httpcore-4.3.3.jar & httpmime-4.3.6.jar

Header 进口:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;