简体   繁体   English

通过Android AsyncTask发布多部分表单数据

[英]Posting multipart form data via Android AsyncTask

My issue is with the writeArgsToConn() function.....i think. 我的问题是与writeArgsToConn()函数有关的。 I cant figure out how to implement it. 我不知道如何实现它。

I am trying to post multipart-formdata from an Android device using AsyncTask class. 我正在尝试使用AsyncTask类从Android设备发布多部分表单数据。 Can anyone help with this? 有人能帮忙吗? I want to stay away from the depreciated org.apache.http.legacy stuff and stick with up-to-date Android libraries. 我想远离折旧的org.apache.http.legacy之类的东西,并坚持使用最新的Android库。

I was able to use similar implementation for a class called DoPostJSON which used Content-Type: application/json and that class works fine. 我可以对名为DoPostJSON的类使用类似的实现,该类使用Content-Type:application / json,并且该类工作正常。

Same question but on Reddit: https://redd.it/49qqyq 同样的问题,但在Reddit上: https : //redd.it/49qqyq

I had issues with getting nodejs express server to detect the parameters being sent in. My DoPostJSON class worked fine and my nodejs server was able to detect parameters...for some reason DoPostMultiPart doesnt work and nodejs server cant see paramters being passed in. I feel like I am using the library the wrong way. 我在使nodejs express服务器检测发送的参数时遇到问题。我的DoPostJSON类工作正常,而我的nodejs服务器也能够检测参数...由于某种原因,DoPostMultiPart无法正常工作,而nodejs服务器看不到传入的参数。感觉我使用图书馆的方式错误。

public class DoPostMultiPart extends AsyncTask<JSONObject, Void, JSONObject> implements Post{

    @Override
    public HttpURLConnection createConn(String action) throws Exception{
        URL url = new URL(Utils.host_api + action);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Cache-Control", "no-cache");

        conn.setReadTimeout(35000);
        conn.setConnectTimeout(35000);
        return conn;
    }

    @Override
    public JSONObject getResponse(HttpURLConnection conn) throws Exception {
        int responseCode = conn.getResponseCode();
        String response = "";
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(conn.getInputStream());
            BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = responseStreamReader.readLine()) != null)
                stringBuilder.append(line).append("\n");
            responseStreamReader.close();
            response = stringBuilder.toString();
        } else {
            throw new Exception("response code: " + responseCode);
        }
        conn.disconnect();
        return new JSONObject(response);
    }

    // TODO: fix this function
    @Override
    public void writeArgsToConn(JSONObject args, HttpURLConnection conn) throws Exception {
        // define paramaters
        String fullname = args.getString("fullname");
        String email = args.getString("email");
        String password = args.getString("password");
        String confpassword = args.getString("confpassword");
        Bitmap pic = (Bitmap) args.get("pic");

        // plugin paramters into request
        OutputStream os = conn.getOutputStream();
        // how do I plugin the String paramters???
        pic.compress(Bitmap.CompressFormat.JPEG, 100, os); // is this right???
        os.flush();
        os.close();
    }

    @Override
    protected JSONObject doInBackground(JSONObject... params) {
        JSONObject args = params[0];
        try {
            String action = args.getString("action");
            HttpURLConnection conn = createConn(action);
            writeArgsToConn(args, conn);
            return getResponse(conn);
        } catch (Exception e) {
            Utils.logStackTrace(e);
            return null;
        }
    }
}

I solved my issue by using OkHttpClient library. 我通过使用OkHttpClient库解决了我的问题。

JSONObject args = params[0];
try
{
    final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    RequestBody requestBody = new MultipartBuilder()
    .type(MultipartBuilder.FORM)
    .addFormDataPart("fullname", args.getString("fullname"))
    .addFormDataPart("email", args.getString("email"))
    .addFormDataPart("password", args.getString("password"))
    .addFormDataPart("confpassword",  args.getString("confpassword"))
    .addFormDataPart("pic", "profile.png", RequestBody.create(MEDIA_TYPE_PNG, (File) args.get("pic")))
    .build();

    Request request = new Request.Builder()
    .url(Utils.host_api + args.getString("action"))
    .post(requestBody)
    .build();

    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
    return new JSONObject(response.body().string());
}
catch (Exception e)
{
    Utils.logStackTrace(e);
    return null;
}

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

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