本文介绍了Java中的Skyscanner API示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Java中建立一个Skyscanner API请求示例 - 但我做了一些错误的事情 - 用于skyscanner API测试的链接:



这里是我到目前为止的测试代码 - 我得到一个内部服务器错误。

任何人都可以在这个例子中看到什么是不正确的?



谢谢




  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;
导入org.apache.http.HttpEntity;
导入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;
导入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<>();
字符串API_KEY =prtl6749387986743898559646983194;
// params.put(apiKey,API_KEY);
params.put(Country,GB);
params.put(货币,GBP);
params.put(Locale,en-GB);
params.put(成人,2);
params.put(Children,2);
params.put(婴儿,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,经济);
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请求=新的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);
}

静态类JsonrpcRequest {
private String jsonrpc =2.0;
私有字符串方法;
私人字符串ID;
私人地图< 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(){
返回Collections.unmodifiableMap(params);
}
public void setParams(Map< String,Object> params){
this.params = params;
}
}
静态类JsonResponseHandler实现了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();
返回实体== null? null:EntityUtils.toString(entity,ENCODING_UTF8);




解决方案

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

  import java.io.BufferedReader; 
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
导入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 =新的URL(请求);
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 =国际航空运输协会&安培;成人= 1\" ;
byte [] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;

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

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

int responseCode = conn.getResponseCode();
System.out.println(\\\
发送'POST'请求到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);
}
}
}

请记得更改YOUR_API_KEY您的apiKey由skyscanner提供。



希望对任何人都有帮助。


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);
    }
}
}
解决方案

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.

这篇关于Java中的Skyscanner API示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 13:57