1

My issue is with the writeArgsToConn() function.....i think. I cant figure out how to implement it.

I am trying to post multipart-formdata from an Android device using AsyncTask class. 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.

I was able to use similar implementation for a class called DoPostJSON which used Content-Type: application/json and that class works fine.

Same question but on 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.

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;
        }
    }
}
IndoNinja
  • 53
  • 8
  • Use some http library to help you with that. It's such a waste of time writing custom json http stuff. – zapl Mar 09 '16 at 23:30
  • Possible duplicate of [Android- POST multipart form data](http://stackoverflow.com/questions/7645284/android-post-multipart-form-data) – Samuel Mar 09 '16 at 23:31
  • Yes, I am inexperienced in Android http request stuff. I was wondering if people could point me in the right direction for which library to go for. Not really sure whats out there. – IndoNinja Mar 09 '16 at 23:32
  • I looked at that post but I had issues with getting my server to see the parameters being passed in. That post didn't help me at all. – IndoNinja Mar 09 '16 at 23:34

1 Answers1

0

I solved my issue by using OkHttpClient library.

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;
}
IndoNinja
  • 53
  • 8