HttpURLConnection returns 400, but request body is correct
<p>I'm trying to connect a java application to the json api of betaface.
I ran into a weird problem I hope you guys can help me with.</p>

<p>I have the (ugly) code to connect to the api. This code is just to test what kind of responses I get and what to do with it.</p>

<p>I build a request body, print the request body to the console, and then write the request body to the api. The problem is that the responsecode is 400.</p>

<p>The weird thing is, when I copy the request body and execute it through Advanced Rest Client it will return a 200 and the expected body. I think the problem is not in the body but somewhere in the HTTPUrlConnection.</p>

<p>I've added my test class to illustrate the problem, you guys would only need a small image to reproduce the problem. The API keys are the free to use api keys of betaface.</p>

<p>Thank you very much for any help you can give me.</p>

<pre><code>import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Base64;

import javax.imageio.ImageIO;

public class APITest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try
        {
            new APITest();
        }
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public APITest() throws MalformedURLException, IOException {
        String api_key = "d45fd466-51e2-4701-8da8-04351c872236";
        String api_secret = "171e8465-f548-401d-b63b-caf0dc28df5f";
        String urlToConnect = "http://www.betafaceapi.com/service_json.svc/UploadNewImage_File";
        File fileToUpload = new File("C:\\test.jpg");
        byte[] t = getImageBase64ByteArray(fileToUpload);
        String body = "";
        body += "{\"api_key\":\"";
        body += api_key;
        body += "\",\"api_secret\":\"";
        body += api_secret;
        body += "\",\"detection_flags\":\"\",\"imagefile_data\":[";
        for(int i = 0; i &lt; t.length; i++) {
            body += t[i];
            if(i &lt; t.length - 1)
                body += ",";
        }
        body += "],\"original_filename\":\"Test.jpg\"}";
        System.out.println(body);
        HttpURLConnection connection = (HttpURLConnection)new URL(urlToConnect).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        BufferedWriter writer = 
                        new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
        writer.write(body);
        writer.newLine();
        writer.flush();
        writer.close();
        int responseCode = connection.getResponseCode();

        System.out.println(responseCode); // Should be 200
        InputStream errorstream = connection.getErrorStream();
        BufferedReader br = null;
        if (errorstream == null){
            InputStream inputstream = connection.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputstream));
        }else{
            br = new BufferedReader(new InputStreamReader(errorstream));
        }
        String response = "";
        String line;
        while ((line = br.readLine()) != null){
            response += line;
        }
        System.out.println(response);
    }

    public byte[] getImageBase64ByteArray(File file) {
        BufferedImage bufferedImage;
        try
        {
            bufferedImage = ImageIO.read(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String encoded = "";
            try {
            ImageIO.write(bufferedImage, "jpg", bos);
            byte[] imageBytes = bos.toByteArray();
            encoded = Base64.getEncoder().encodeToString(imageBytes);
            bos.close();
            } catch (IOException e) {
            e.printStackTrace();
            }
            return encoded.getBytes();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return new byte[0];
    }
}
</code></pre>