0

I am trying to upload an image file in my android app, But I am getting Response code 400 and responseMessage = null. The API accepts an image file and one more extra field as POST message.

Following is my code:

public String sendPostRequest(String requestURL,
                              HashMap<String, String> postDataParams) {

    URL url;

    StringBuilder sb = new StringBuilder();
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);


        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();
        int responseCode = conn.getResponseCode();

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            sb = new StringBuilder();
            String response;
            while ((response = br.readLine()) != null){
                sb.append(response);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

Edit

My above function is defined in file RequestHandler and it is being called from Activity as following:

public void uploadImage(){

    final String text = editText.getText().toString().trim();
    final String image = getStringImage(bitmap);
    class UploadImage extends AsyncTask<Void,Void,String> {
        ProgressDialog loading;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            loading = ProgressDialog.show(FileUploadActivity.this,"Please wait...","uploading",false,false);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            loading.dismiss();
            Toast.makeText(FileUploadActivity.this,s,Toast.LENGTH_LONG).show();
        }

        @Override
        protected String doInBackground(Void... params) {
            RequestHandler rh = new RequestHandler();
            HashMap<String,String> param = new HashMap<String,String>();
            param.put(KEY_TEXT,text);
            param.put(KEY_IMAGE,image);
            String result = rh.sendPostRequest(UPLOAD_URL, param);
            return result;
        }
    }
    UploadImage u = new UploadImage();
    u.execute();
}

Edit2: Following function is also part of RequestHandler

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}
halfer
  • 19,824
  • 17
  • 99
  • 186
pankaj
  • 7,878
  • 16
  • 69
  • 115

2 Answers2

0

Http 400 means "Bad Request. The request could not be understood by the server..." so first thing first you should show how you compose your request in your getPostDataString() function.

I bet you are not using multipart form data. See this SO answer

corradolab
  • 718
  • 3
  • 16
0

I can't comment yet so I provide it like answer. This is a weird API. Are you sure that you understood it correctly? You use POST method, but do not provide Content Type. This is neither JSON nor XML. This is plain string formatted like URL request. I'm not surprised that server return 400. Check API description.