1

I want to send post request in android using Asynctask but it did not work. In post man I send raw data bellow and I got the result.

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename="file name"
Content-Type: image/jpeg
Content-Encoding: base64

------------
/9j/wAARCAQ4B4ADASEAAhEBAxEB/90ABAB4/9sAhAADAgIDAgIDAwMDBAMDBAYJBgYEBAY
MCAgHCQ4MDg4NDA0NEBEWExARFBENDRMbExQXGBkZGQ4SHB0bGB0WGBkYAQMEBAYEBgsGBg
sYEA0QGBgYG....
------WebKitFormBoundary7MA4YWxkTrZu0gW--

My code in android:

public class HttpAsyncTask extends AsyncTask<String, String, String> {

    public HttpAsyncTask(){
        //set context variables if required
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0]; // URL to call
        String data = params[1]; //data to post
        OutputStream out = null;
        String response = "";

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("image", data);
            urlConnection.setDoOutput(true);

            out = new BufferedOutputStream(urlConnection.getOutputStream());

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();
            int responseCode=urlConnection.getResponseCode();
            Log.i("responseCode ", Integer.toString(responseCode));
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br =new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

            }

//            urlConnection.connect();
        } catch (Exception e) {
            Log.i("HTTP async task", e.toString());
        }

        Log.i("HTTP async task", response);

        return response;
    }

    @Override
    protected void onPostExecute(String response) {
        Log.i("HTTP async task", response);
        super.onPostExecute(response);
    }
}

Then I call new HttpAsyncTask().execute(myurl, based64String);

user1506104
  • 6,554
  • 4
  • 71
  • 89
  • Possible duplicate of [Upload multiple image file using HttpURLConnection](https://stackoverflow.com/questions/32984323/upload-multiple-image-file-using-httpurlconnection) – user1506104 Aug 26 '19 at 04:13

0 Answers0