3

我正在尝试用 Java 构建一个请求 Skyscanner API 的示例——但我做错了——skyscanner API 测试的链接:http: //business.skyscanner.net/portal/en-GB/Documentation/FlightsLivePricingQuickStart

这是我到目前为止的测试代码 - 我收到“内部服务器错误”。

任何人都可以看到此示例中的不正确之处?

谢谢


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);
    }
}
}
4

1 回答 1

2

我知道这是一个老问题,但我花了很多时间来找到一个适用于 Java 的示例,所以我在这里发布了我已经完成的解决方案。我使用了 HttpClient 和 HttpPost 类的 HttpUrlConnection。

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);
    }
}
}

请记住为您的 apiKey 更改由 skyscanner 提供的“YOUR_API_KEY”。

希望它对任何人都有帮助。

于 2016-08-23T07:47:53.323 回答