本文介绍了如何在Heroku上使用JAX-RS查找传入的RESTful请求的IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于一个示例编写Heroku上托管的Java RESTful服务 - >

I'm writing a Java RESTful service hosted on Heroku based on an example -> https://api.heroku.com/myapps/template-java-jaxrs/clone

我的示例服务是:

My sample service is:

package com.example.services;

import com.example.models.Time;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeService {

    @GET
    public Time get() {
        return new Time();
    }

}

我的主要是:

public class Main {

    public static final String BASE_URI = getBaseURI();

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception{
        final Map<String, String> initParams = new HashMap<String, String>();
        initParams.put("com.sun.jersey.config.property.packages","services.contracts");

        System.out.println("Starting grizzly...");
        SelectorThread threadSelector = GrizzlyWebContainerFactory.create(BASE_URI, initParams);
        System.out.println(String.format("Jersey started with WADL available at %sapplication.wadl.",BASE_URI, BASE_URI));
    }

    private static String getBaseURI()
    {
        return "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";
    }

}

我的问题是如何找到在我的服务中输出请求来自的IP地址和端口组合?我已阅读@Context上的内容,其中注入了javax.ws.rs.core.HttpHeaders,javax.ws.rs.core.Request等。但是,不存在传入的IP或端口信息。

My question is how can I find out in my service the IP address and port combination the request is coming from? I've read stuff on @Context which injects javax.ws.rs.core.HttpHeaders, javax.ws.rs.core.Request, etc. However, no incoming IP or port info is present.

我知道如果你实现了com.sun.grizzly.tcp.Adapter,你可以这样做:

I know if you implement com.sun.grizzly.tcp.Adapter, you can do something like:

public static void main(String[] args) {
    SelectorThread st = new SelectorThread();
    st.setPort(8282);
    st.setAdapter(new EmbeddedServer());
    try {
        st.initEndpoint();
        st.startEndpoint();
    } catch (Exception e) {
        System.out.println("Exception in SelectorThread: " + e);
    } finally {
        if (st.isRunning()) {
            st.stopEndpoint();
        }
    }
}

public void service(Request request, Response response)
        throws Exception {
    String requestURI = request.requestURI().toString();

    System.out.println("New incoming request with URI: " + requestURI);
    System.out.println("Request Method is: " + request.method());

    if (request.method().toString().equalsIgnoreCase("GET")) {
        response.setStatus(HttpURLConnection.HTTP_OK);
        byte[] bytes = "Here is my response text".getBytes();

        ByteChunk chunk = new ByteChunk();
        response.setContentLength(bytes.length);
        response.setContentType("text/plain");
        chunk.append(bytes, 0, bytes.length);
        OutputBuffer buffer = response.getOutputBuffer();
        buffer.doWrite(chunk, response);
        response.finish();
    }
}

public void afterService(Request request, Response response)
        throws Exception {
    request.recycle();
    response.recycle();
}

和存取

and access

    request.remoteAddr()

但我真的很喜欢以更结构化的方式分离我的RESTful API,就像我在第一次执行时那样。

But I'd really like to separate my RESTful API in a more structured way like in my first implementation.

任何帮助都将不胜感激。感谢!

Any help would be greatly appreciated. Thanks!

推荐答案

正如Luke所说,使用Heroku时,远程主机是AWS应用程序层,因此是EC2的ip地址。

As Luke said, when using Heroku, the remote host is the AWS application tier, therefore the EC2 ip address.

X-Forwarded-For标题是答案:

"X-Forwarded-For" header is the answer:

String ip = "0.0.0.0";
try {
    ip = req.getHeader("X-Forwarded-For").split(",")[0];
} catch (Exception ignored){}

这篇关于如何在Heroku上使用JAX-RS查找传入的RESTful请求的IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 19:33
查看更多