2

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.

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.

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.

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.

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.

Thank you very much for any help you can give me.

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 < t.length; i++) {
            body += t[i];
            if(i < 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];
    }
}
7
  • As mentioned in the problems description the keys are public free to use anonymous keys on the public pages of the betaface api. I left them there on purpose for easy testing.
    – JohannisK
    Jun 22, 2016 at 10:26
  • Why you are creating JSON manually ?? it is not a good practice..!! Jun 22, 2016 at 10:27
  • I know, but this problem occored when I was just testing the api. The bad JSON creation is not related to the problem I'm describing. I want to figure out why I get a 400 response when the request body returns a 200 response in another client.
    – JohannisK
    Jun 22, 2016 at 10:28
  • 1
    Try adding the 'Content-Length' header, which may be added automatically by the Advanced Rest Client
    – yonisha
    Jun 22, 2016 at 10:32
  • 1
    have you specified the type of request ?? @JohannisK Jun 22, 2016 at 10:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.