How does a server actually identify the requesting client address (IP), and send a response?
Is it possible to get the IP address of requesting client in GAE?
In a Java servlet you could use request.getRemoteAddr():
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
String ipAddress = req.getRemoteAddr();
}
If you are using Appengine with Go, the Request object contains the address in the string field RemoteAddr:
import (
"fmt"
"net/http"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.RemoteAddr)
}
Related
I have Jsoup code and successfully send request.Also this code work fine in hide/change 'X-Forwarded-For' Header data, but i cant hide/change Remote/System Ip Address.
Client Side Code:
Document doc = Jsoup.connect("http://192.168.XX.XX:XXXX/microFin/XXXX")
.header("X-Forwarded-For", "192.168.0.1").get();
Server Side Code:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String authCredentials = request.getHeader("Authorization");
String pathInfo = request.getServletPath();/////api/auth
String ip = request.getHeader("X-Forwarded-For");
String ip11 = request.getRemoteAddr();
if (ip == null) {
ip = request.getRemoteAddr();
}
System.out.println("IP-ADDRESS::" + ip);//192.168.0.1
System.out.println("IP-ADDRESS::" + ip11);//actual ip ???
If any solution for change System Ip then please help me.
You can use a VPN service to hide the IP address of the client machine. There are several software ranging from premium to paid.
My software of preference is: TunnelBear Link
I'm creating a function that doesn't take an HttpServletRequest object as an argument because depending on the session (it could be either through a mobile device or a web browser). If it's a mobile device, it uses the latitude and longitude, or if its from a web browser, I want to be able to grab the IP address. Is there a way to achieve this? Every examples I saw takes an HttpServletRequest as an argument.
This is an example of what I would like to accomplish, if possible.
public String getLocation(Session session) {
switch(session.getLocation()) {
case Mobile:
System.out.printf("Latitude is %s and Longitude is %s\n", session.getLatitude(), session.getLongitude());
break;
case Web:
HttpServletRequest request;
String ipAddress = request.getRemoteAddr();
System.out.printf("The IP Adress is %s", ipAddress);
break;
default:
System.out.print("Error\n");
break;
}
}
An IP address is a property of a request. Session may correspond to many requests (that comprise that session), and they may come from different IP addresses. So it is not possible to derive a unique IP address from a Session in some 'standard' way.
But what you can do is store an IP address from request to its session in a filter. For example, each request could simply write its IP address to the session's attribute, so at any moment you'd have access to the IP address of the last request in that session. Or you could implement some Accumulator and store it in your session and put request's IP address to that Accumulator which would implement some logic (like choosing 'the most popular' IP address, or do something else). That's up to you.
How to implement the filter:
public class RequestIPSavingFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
if (req instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) req;
final String ipAddress = request.getRemoteAddr();
Accumulator accumulator = (Accumulator) request.getSession().getAttribute("accumulator");
if (accumulator == null) {
accumulator = new Accumulator();
request.getSession().setAttribute("accumulator", accumulator);
}
accumulator.putIpAddress(ipAddress);
}
chain.doFilter(req, resp);
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}
Later, in your session processing code, you do
Accumulator accumulator = (Accumulator) request.getSession().getAttribute("accumulator");
and use accumulator.getBestIpAddress()
I want to submit form data to servlet which is Jersey rest client
and inside this servlet I have to call a Restful Webservice.
I have to pass all form data to that rest Webservice and after that we will get a response object from rest to servlet.
I have to pass this response object directly to JSP page here request and response will be in JSON format.
you can use servlet to send data to web service by sendRedirect("<url>")
Is it really necessary to call REST Class from a Servlet?
If so, the following is the way. But your REST call will be treated as a plain class. To call any method of the Rest class you have to create its object and access its methods.
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI();
RestClass restClassObj = new RestClass();
String parameter1 = "";
String parameter2 = "";
String parameter3 = "";
String restResponse = "";
if(StringUtils.endsWith(requestURI, "services") || StringUtils.endsWith(requestURI, "services/")){
parameter1 = req.getParameter("parameter1");
parameter2 = req.getParameter("parameter2");
parameter3 = req.getParameter("parameter3");
restResponse = restClassObj.getRestClassMethodResponse(parameter1,parameter2,parameter3);
}
resp.setContentType("application/json");
resp.getWriter().write(restResponse);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
Now the RestClass is,
public class RestClass {
public RestClass() {
}
public String getRestClassMethodResponse(#FormParam("parameter1") String parameter1, #FormParam("parameter2") String parameter2, #FormParam("parameter3") String parameter3){
//Now write your own logic and return the data to the Servlet class in //JSON format
return jsonResponse;
}
}
I am trying to use RequestBuilder in GWT to see if Accept-Ranges is supported.
Following is my client code:
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET,pathToServlet);
builder.setHeader("Range","bytes=0-10");
RequestCallback callback = new RequestCallback() {
#Override
public void onError(Request arg0, Throwable arg1) {
}
#Override
public void onResponseReceived(Request req, Response res) {
log.info("Text:"+res.getText());
log.info("Code:"+res.getStatusCode());
}
};
try {
builder.sendRequest(null, callback);
} catch (RequestException e) {}
And my servlet code is just a simple test code:
public class RangeTest extends HttpServlet{
static Logger log = Logger.getLogger(RangeTest.class);
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String output = new String("This is a test string to be sent to the client");
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.println(output);
}
}
In the output I get on the client, following is printed:
Text:This is a test string to be sent to the client
Code:200
What I expected was, since I gave the range header as 0-10 in the request, only the first 10 bytes will be sent to the client. But here the entire string is getting sent. What am I doing wrong here? Is there anything I have missed?
I feel my comment is more readable for other as answer (and effectively it is one):
You are not evaluating the range-header in your servlet-method. And the super class HttpServlet does not evaluate it either (but DefaultServlet from Tomcat).
The servlet specification has left most of the implementation work to providers like Apache. This explains why API classes like HttpServlet does not do the work of interpreting special http headers, but provider classes like the mentioned Tomcat-DefaultServlet. The main purpose of a specification is mainly to enable different implementations not to force people to only one.
I have an ajax request function (written in JavaScript) and Java Servlet that handles this request. I need to get all request parameters and if it succeeded then send back a confirmation that it has succeeded. How I can send a confirmation message? As an attribute, like {isSuccess: true}. My code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
Enumeration<?> paramNames = request.getParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = (String) paramNames.nextElement();
// storing data fn
}
// how to send back a message here?
}
Get PrintWriter object by calling HttpServletResponse#getWriter and write your String.
response.getWriter().write("{isSuccess: true}");