0

I try to make a small app that take a Camera Bitmap and other data and send them to a REST API server in Json format. So far I have written the code below, but I get the error code 400 Bad request :(

This is in MainActivity

private void SendPictureToServer(String sPhoto) {

try {
    String baseUrl = "http://192.168.0.1:7100/api/v1/save/img";
    String username = "52363cc0cb3a442ebc98ba399f47ca3d";  // <= api key
    String password = "";

    JSONObject postData = new JSONObject();
    postData.put("pl", "1");
    postData.put("id", "76885");
    postData.put("name", "photo");
    postData.put("ext", "jpg");
    postData.put("type", "Product picture #1");
    postData.put("img", sPhoto);

    ApiClient apiClient = new ApiClient(baseUrl, username, password);
    AsyncTask<Void, Void, String> execute = new ExecuteNetworkOperation(apiClient, postData.toString(), "POST");
    execute.execute();
} catch (Exception e) {
    e.printStackTrace();
}

}

This is also in MainActivity

public class ExecuteNetworkOperation extends AsyncTask<Void, Void, String> {

private ApiClient apiClient;
private String isValidCredentials = "";
private String postData = "";
private String httpMethod = "";

public ExecuteNetworkOperation(ApiClient apiClient, String postData, String httpMethod) {
    this.apiClient = apiClient;
    this.postData = postData;
    this.httpMethod = httpMethod;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    // Display the progress bar.
    // findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
}

@Override
protected String doInBackground(Void... params) {
    try {
        if (httpMethod == "POST" && !TextUtils.isEmpty(postData))
        {
            apiClient.setHttpMethod("POST");
            isValidCredentials = apiClient.executePostData(postData);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Hide the progress bar.
    //findViewById(R.id.loadingPanel).setVisibility(View.GONE);

    if (isValidCredentials.equals("true")) {
        Toast.makeText(getApplicationContext(), "Successful connection", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(getApplicationContext(), "Login error", Toast.LENGTH_LONG).show();
    }
}

}

And this is in ApiClient.java

public class ApiClient {

private String baseUrl;
private String username;
private String password;
private String urlResource;
private String urlPath;
private String lastResponse;
private String payload;
private String httpMethod;
private HashMap<String, String> parameters;
private Map<String, List<String>> headerFields;

public ApiClient(String  baseUrl, String username, String password) {
    setBaseUrl(baseUrl);
    this.username = username;
    this.password = password;
    this.urlResource = "";
    this.urlPath = "";
    this.httpMethod = "";
    parameters = new HashMap<>();
    lastResponse = "";
    payload = "";
    headerFields = new HashMap<>();
    // This is important. The application may break without this line.
    System.setProperty("jsse.enableSNIExtension", "false");
}

public ApiClient setBaseUrl(String baseUrl) {
    this.baseUrl = baseUrl;
    if (!baseUrl.substring(baseUrl.length() - 1).equals("/")) {
        this.baseUrl += "/";
    }
    return this;
}

public ApiClient setHttpMethod(String httpMethod) {
    this.httpMethod = httpMethod;
    return this;
}

public ApiClient clearAll() {
    parameters.clear();
    baseUrl = "";
    this.username = "";
    this.password = "";
    this.urlResource = "";
    this.urlPath = "";
    this.httpMethod = "";
    lastResponse = "";
    payload = "";
    headerFields.clear();
    return this;
}   


public String executePostData(String postJsonData) {
    StringBuilder outputStringBuilder = new StringBuilder();

    try {
        String userCredentials = new String(username + ":" + password);
        String basicAuth = "Basic " + Base64.encodeToString(userCredentials.getBytes(), Base64.NO_WRAP);

        URL url = new URL(this.baseUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty ("Authorization", basicAuth);
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000);

        try {

            OutputStream outputStream = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            writer.write(postJsonData);
            writer.flush();
            writer.close();
            outputStream.close();

            headerFields = connection.getHeaderFields();
            int responseCode = connection.getResponseCode();
            String responseMess = connection.getResponseMessage();
            InputStream errorStream = connection.getErrorStream();

            Log.e("postJsonData ", postJsonData);
            Log.e("headerFields ", headerFields.toString());
            Log.e("ResponseCod ", String.valueOf(responseCode));
            Log.e("ResponseMessage ", responseMess);
            Log.e("ErrorStream ", errorStream.toString());


            if (responseCode == HttpURLConnection.HTTP_OK) {
                outputStringBuilder.append("true : ");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    outputStringBuilder.append(line);
                }
                bufferedReader.close();
            }else {
                outputStringBuilder.append(new String("false : "+responseCode +" " + responseMess + " " + errorStream.toString()));
            }


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return outputStringBuilder.toString();
}

}

This is from Logcat

07-03 18:32:19.427 30515-31533 E/headerFields: {null=[HTTP/1.1 400 Bad Request], Content-Length=[0], Date=[Tue, 03 Jul 2018 15:31:07 GMT], Server=[Microsoft-HTTPAPI/2.0], X-Android-Received-Millis=[1530631939426], X-Android-Response-Source=[NETWORK 400], X-Android-Selected-Protocol=[http/1.1], X-Android-Sent-Millis=[1530631939299]}
07-03 18:32:19.427 30515-31533 E/ResponseCod: 400
07-03 18:32:19.428 30515-31533 E/ResponseMessage: Bad Request
07-03 18:32:19.428 30515-31533 E/ErrorStream: buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()
07-03 18:32:19.428 30515-30515 E/isValidCredentials: false : 400 Bad Request buffer(com.android.okhttp.internal.http.Http1xStream$FixedLengthSource@ccbe20f).inputStream()
2
  • 1
    You should check your url and make sure it is not badly formed or modified along the way. This error pops up when the url is not formed properly. Commented Jul 3, 2018 at 19:03
  • Thank you! I tested with an external IP from hurl.eu and the url/request is good and post it correctly the Json data. Anyway, I'll check once again. Commented Jul 4, 2018 at 6:49

2 Answers 2

6

This is how I send a POST

Let me know if you need any clarification.

public static String executePost(String targetURL, String requestJSON, String apikey) {
        HttpURLConnection connection = null;
        InputStream is = null;

        try {
            //Create connection
            URL url = new URL(targetURL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            //TODO may be prod or preprod api key
            if (apikey.equals(Constants.APIKEY_PREPROD)) {
                connection.setRequestProperty("Authorization", Constants.APIKEY_PREPROD);
            }
            if (apikey.equals(Constants.APIKEY_PROD)){
                connection.setRequestProperty("Authorization", Constants.APIKEY_PROD);
            }
            connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
            connection.setRequestProperty("Content-Language", "en-US");  
            connection.setUseCaches(false);
            connection.setDoOutput(true);

            //Send request
            System.out.println(requestJSON);
            DataOutputStream wr = new DataOutputStream (
            connection.getOutputStream());
            wr.writeBytes(requestJSON);
            wr.close();

            //Get Response  

            try {
                is = connection.getInputStream();
            } catch (IOException ioe) {
                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConn = (HttpURLConnection) connection;
                    int statusCode = httpConn.getResponseCode();
                    if (statusCode != 200) {
                        is = httpConn.getErrorStream();
                    }
                }
            }

            BufferedReader rd = new BufferedReader(new InputStreamReader(is));


            StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
            String line;
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            return response.toString();
        } catch (Exception e) {

            e.printStackTrace();
            return null;

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Your post was very helpful.Thank you!
great. im glad it helped you solve your issue @AdrianS.
1

This is the solution that worked for me. It has a few small changes starting from the solution offered by DroiDev.

    public static String executePost(String targetURL, String requestJSON, String apikey) {
    HttpURLConnection connection = null;
    InputStream is = null;
    String authKey = "Basic " + Base64.encodeToString((apikey + ":").getBytes(), Base64.NO_WRAP);

    try {
        //Create connection
        URL url = new URL(targetURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Authorization", authKey);
        connection.setRequestProperty("Content-Length", Integer.toString(requestJSON.getBytes().length));
        connection.setUseCaches(false);
        connection.setDoOutput(true);

        //Send request
        DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
        wr.writeBytes(requestJSON);
        wr.close();

        //Get Response
        try {
            is = connection.getInputStream();
        } catch (IOException ioe) {
            if (connection instanceof HttpURLConnection) {
                HttpURLConnection httpConn = (HttpURLConnection) connection;
                int statusCode = httpConn.getResponseCode();
                if (statusCode != 200) {
                    is = httpConn.getErrorStream();
                }
            }
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();

    } catch (Exception e) {

        e.printStackTrace();
        return null;

    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.