我正在编写一个基于Heroku托管的Java RESTful服务,参考示例 -> https://api.heroku.com/myapps/template-java-jaxrs/clone
我的样例服务是:
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或端口信息。
我知道如果你实现com.sun.grizzly.tcp.Adapter,你可以做类似这样的事情:
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();
}
并获得访问权限
request.remoteAddr()
但是我真的希望像我第一次实现时那样,以更加结构化的方式分离我的RESTful API。
非常感谢任何帮助!谢谢!
ip-10-42-223-182.ec2.internal
,看起来是一个 EC2 IP。 - LukeX-Forwarded-For
头。 - Lukepom.xml
文件中包含javax-servlet
用于servlet-api
(http://mvnrepository.com/artifact/javax.servlet/servlet-api/2.5),然后导入`javax.servlet.http.HttpServletRequest`。Context
类已经包含在JAX-RS中:import javax.ws.rs.core.Context
。 - Sonny