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

时间:2016-03-09 23:25:52

标签: java android android-asynctask http-post multipartform-data

我的问题是使用writeArgsToConn()函数.....我想。我无法弄清楚如何实现它。

我正在尝试使用AsyncTask类从Android设备发布multipart-formdata。有人能帮忙吗?我想远离贬值的org.apache.http.legacy东西,并坚持使用最新的Android库。

我能够对一个名为DoPostJSON的类使用类似的实现,该类使用了Content-Type:application / json,并且该类工作正常。

同样的问题,但在Reddit:https://redd.it/49qqyq

我遇到了让nodejs表达服务器来检测正在发送的参数的问题。我的DoPostJSON类工作正常,我的nodejs服务器能够检测参数......由于某种原因,DoPostMultiPart无法正常工作,而nodejs服务器无法看到传递参数in。我觉得我错误地使用了这个库。

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

1 个答案:

答案 0 :(得分:0)

我使用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;
}