Skyscanner API example in Java

2019-05-11 23:19发布

问题:

I am trying to build an example of request for Skyscanner API in Java - but I am doing something wrong - the link for skyscanner API test: http://business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingQuickStart

Here is the test code I have so far - I get an "Internal Server Error".

Anyone can see what is incorrect in this example?

Thanks


package FLIGHTS;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class Test {
    public static final String HTTP_HEADER_X_APPLICATION = "X-Application";
    public static final String HTTP_HEADER_X_AUTHENTICATION = "X-Authentication";
    public static final String HTTP_HEADER_CONTENT_TYPE = "Content-Type";
    public static final String HTTP_HEADER_ACCEPT = "Accept";
    public static final String HTTP_HEADER_ACCEPT_CHARSET = "Accept-Charset";
    public static String ENCODING_UTF8 = "UTF-8";    

    public static void main(String[] args) throws IOException {
        HashMap<String, Object> params = new HashMap<>();
        String API_KEY = "prtl6749387986743898559646983194";
//        params.put("apiKey", API_KEY);
        params.put("Country", "GB");
        params.put("Currency", "GBP");
        params.put("Locale", "en-GB");
        params.put("Adults", 2);
        params.put("Children", 2);
        params.put("Infants", 0);
        params.put("OriginPlace", 11235);
        params.put("DestinationPlace", 13554);
        params.put("OutboundDate", "2016-01-23");
        params.put("InboundDate", "2016-01-30");
        params.put("LocationSchema", "Default");
        params.put("CabinClass", "Economy");
        params.put("GroupPricing", true);
        String url = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/?apikey="+API_KEY;
        System.out.println(url);
        HttpPost post = new HttpPost(url);
        JsonrpcRequest request = new JsonrpcRequest();
        request.setParams(params);
        request.setMethod("POST");
        request.setId("1");
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX").create();
        String jsonRequest = gson.toJson(request);        

        System.out.println(jsonRequest);
        post.setHeader(HTTP_HEADER_CONTENT_TYPE, "application/x-www-form-urlencoded");
        post.setHeader(HTTP_HEADER_ACCEPT, "application/json" );
        post.setHeader(HTTP_HEADER_ACCEPT_CHARSET, ENCODING_UTF8 ); 
        post.setEntity(new StringEntity(jsonRequest, ENCODING_UTF8));
        HttpClient httpClient = new DefaultHttpClient();
        JsonResponseHandler reqHandler = new JsonResponseHandler();
        String resp = httpClient.execute(post, reqHandler);
        System.out.println(resp);
    }

    static class JsonrpcRequest {
        private String jsonrpc = "2.0";
        private String method;
        private String id;
        private Map<String, Object> params;

        public String getJsonrpc() {
            return jsonrpc;
        }
        public void setJsonrpc(String jsonrpc) {
            this.jsonrpc = jsonrpc;
        }
        public String getMethod() {
            return method;
        }
        public void setMethod(String method) {
            this.method = method;
        }
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public Map<String, Object> getParams() {
            return Collections.unmodifiableMap(params);
        }
        public void setParams(Map<String, Object> params) {
            this.params = params;
        }
    }
    static class JsonResponseHandler implements ResponseHandler<String> {

    @Override
    public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            throw new HttpResponseException(statusLine.getStatusCode(),
                    statusLine.getReasonPhrase());
    }
    HttpEntity entity = response.getEntity();
        return entity == null ? null : EntityUtils.toString(entity, ENCODING_UTF8);
    }
}
}

回答1:

I know it's an old question but I spent a lot of time to find an example that works in Java so I post here the solution that I've done. I used the HttpUrlConnection insted of the HttpClient and HttpPost classes.

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;


public class FlightsJava {

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

    String request        = "http://partners.api.skyscanner.net/apiservices/pricing/v1.0/";
    URL    url            = new URL( request );
    HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
    conn.setDoOutput( true );
    conn.setInstanceFollowRedirects( false );
    conn.setRequestMethod( "POST" );
    conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); 
    conn.setRequestProperty("Accept", "application/json");
    conn.setRequestProperty( "charset", "utf-8");


    String urlParameters = "apiKey=YOUR_API_KEY&country=BR&currency=BRL&locale=pt-BR&originplace=SDU&destinationplace=GRU&outbounddate=2016-09-23&locationschema=Iata&adults=1";   
    byte[] postData       = urlParameters.getBytes( StandardCharsets.UTF_8 );
    int    postDataLength = postData.length;

    conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));

    conn.setUseCaches( false );
    try{
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.write(postData);
        wr.flush();
        wr.close();

        int responseCode = conn.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);
        System.out.println("Header Fields : " + conn.getHeaderFields());
    } catch (Exception e){
        System.out.println(e);
    }
}
}

Remember to change "YOUR_API_KEY" for your apiKey provided by skyscanner.

Hope it helps to anyone.