3

I'm pretty new to software development and I'm working on a project that makes API calls to a transaction server with a bearer token.

I've figured out how to call the API through curl via command line. It looks something like this (it is through http rather than https because I am using their test server which only supports http requests)

curl http://api.testwebsite.com/transactions/ \
-H "Authorization: Bearer <TOKEN ID>" \
-d amount=500 \
-d currency="USD" \
-d card_number="<card number>" \
-d card_exp_month=<exp month> \
-d card_exp_year=<exp year> \
-d card_cvv="<card's ccv>"

Now I'm writing a program in Java (has to be Java) using only native Java libraries (no 3rd party packages like Spring or Apache) and I'm trying to call the API through HttpUrlConnection.

import java.io.BufferedReader; 
import java.io.InputStreamReader;
import java.io.DataOutputStream; 
import java.net.URL;             
import javax.net.ssl.HttpsURLConnection;
import java.net.HttpURLConnection;

public class TestHttpsPost {

public static void main(String[] args) throws Exception {

    // Uncomment one of these next two lines:
    URL url = new URL("http://api.testwebsite.com/transactions");
    //URL url = new URL("https://httpbin.org/post"); // good for testing

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoInput(true);
    connection.setDoOutput(true);

    // Change this to a valid token:
    connection.setRequestProperty("Authorization", "Bearer <TOKEN ID>");
    /*

    connection.setRequestProperty("amount", "500");
    connection.setRequestProperty("currency", "USD");
    connection.setRequestProperty("card_number", "<CARD_NUMBER>");
    connection.setRequestProperty("card_exp_month", "<EXP_MONTH>");
    connection.setRequestProperty("card_exp_year", "<EXP_YEAR");
    connection.setRequestProperty("card_cvv", "<CCV>");
    */




    String jsonData1 = "amount=500";
    String jsonData2 = "currency=\"USD\"";
    String jsonData3 = "card_number=\"11111111111111111\"";
    String jsonData4 = "card_exp_month=11";
    String jsonData5 = "card_exp_year=2011";
    String jsonData6 = "card_cvv=\"123\"";




    try {
        // Post the data:
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.writeBytes(jsonData1);
        output.writeBytes(jsonData2);
        output.writeBytes(jsonData3);
        output.writeBytes(jsonData4);
        output.writeBytes(jsonData5);
        output.writeBytes(jsonData6);

        output.close();

        // Read the response:
        BufferedReader reader = new BufferedReader(new InputStreamReader(
          connection.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        reader.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    System.out.println("Response code:" + connection.getResponseCode());
    System.out.println("Response message:" + connection.getResponseMessage());
}
}

But I keep getting

Server returned HTTP response code: 400 for URL: http://api.testwebsite.com/transactions
Response code:400
Response message:Bad Request

I followed Transforming a PayPal curl request to an http request in Java, but the fields for the paypal api are pretty different and I'm not sure if I messed anything up.

Thanks in advance!

Community
  • 1
  • 1
Zekun Wang
  • 31
  • 1
  • 4

1 Answers1

0

Really nice options is to use Retrofit (a type -safe http client for java and Android)

http://square.github.io/retrofit/

this is an example of service with auth token usage:

public class ServiceGenerator {
    public static final String BASE_URL = "https://your.api.url";
    // returns an API client of type serviceClass
    public static <S> S createService(
            Class<S> serviceClass, final String token) {
        RestAdapter.Builder builder = new RestAdapter.Builder() .setEndpoint(BASE_URL)
                .setClient(new OkClient(new OkHttpClient()));
        if (token != null) {
            builder.setRequestInterceptor(new RequestInterceptor() {
                @Override
                public void intercept(RequestFacade request) { request.addHeader("Accept", "application/json"); request.addHeader("Authorization", token);
                } });
        }
        RestAdapter adapter = builder.build();
        return adapter.create(serviceClass); }
}
Bogdan Ustyak
  • 5,639
  • 2
  • 21
  • 16