Java check http request

How to Test Java HTTP Client Usages (e.g. OkHttp, Apache HttpClient)

Fetching data via HTTP from a remote system is a task almost every application has to solve. Fortunately, there are mature Java HTTP client libraries available that are robust and have a user-friendly API. Most of the frameworks ship their own HTTP client (e.g Spring with WebClient and RestTemplate , Jakarta EE with the JAX-RS Client), but there are also standalone clients available: OkHttp, Apache HttpClient, Unirest, etc. When it comes to testing Java classes that use one of these clients, I often see developers trying to mock the internals of the library. With this article, you’ll understand why such an approach is not beneficial and what you should do instead when writing a test that involves a Java HTTP client.

Why Plain Old Unit Tests Are Not Enough

Most of the Java HTTP clients are instantiated with static methods. In addition, we usually chain multiple method calls or use a builder to construct the instance of the client or the HTTP request.

Even though Mockito is able to mock static method calls and with deep mocking, we could keep the stubbing setup lean, we should always remember:

Every time a mock returns a mock a fairy dies.

We end up in a mocking hell and have to mock the whole setup. With this approach, we also almost duplicate our production code as the stubbing setup has to match our usage.

While we could test conditionals e.g. behavior on non 200 HTTP responses or how our implementation handles exceptions, there is not much benefit with this approach.

A better solution for testing our Java HTTP clients would be to actually test them in action and see how they behave to different responses. This also allows us to test more niche scenarios like slow responses, different HTTP status codes, etc.

A Better Approach for Testing HTTP Clients

Instead of heavy lifting with Mockito, we’ll spawn a local web server and queue HTTP responses. We can then let our HTTP clients connect to this local server and test our code.

Whether or not we are still writing a unit test depends on your definition and scope. However, we are still testing a unit of our application in isolation. Going further, we also have to take a small overhead (time-wise) into account. Most of the time this is negligible.

The two most common libraries for this are WireMock and the MockWebServer from OkHttp. We’ll use the lightweight MockWebServer for this demo, but you can achieve the same with WireMock.

Читайте также:  Visual studio code скомпилировать python

There’s already an example on how to use WireMock with JUnit 5 for testing a Spring Boot application on my blog: Spring Boot Integration Tests with WireMock and JUnit 5

We include the MockWebServer with the following Maven import:

Источник

Java check for connection request java

Your better choice is to improve server throughput so that clients don’t have to wait so long. However, you’re rather interested in comparing the content of two different string references, not if they point to the same reference.

How to find out a http request is sent by a local network computer or by an internet client?

I need a structure which check if a request is sent by a local network computer or is sent by a remote client via internet.

Is it possible to get this using httprequest object or ip address?

IF client is a local network computer DO 1 IF Client is a remote computer from internet DO 2 

If you have the HttpServletRequest you can look at the

request.getRemoteAddr() request.getLocalAddr() 

These can be used to determine where the client request came from.

Java — TCP/IP Sending request and getting response, Creating Scoket go through this will help you. if you are implementing Sockets, you need to use ServerSocket class to create the ServerSocket . Then Socket class to request the create the connection between Client and Sever. Share answered Nov 6, 2012 at 12:15 Vijay 1,024 6 18 Add a comment

Check whether an HttpServletRequest’s connection is still open?

Using a synthetic load with both the client and the server running on localhost, I verified via tcpdump and netstat that the client is sending a FIN packet to the server, but the the connection is stuck in CLOSE_WAIT while the request remains queued on the server (I’m using Jetty with a queued thread pool). When a worker thread is available in the pool, the request is processed as usual by the servlet even though the connection has already been closed by the client.

What I want is a way to test whether the connection has already been closed to prevent the server from processing requests that have already timed out on the client side (I know I can set an http header on the client with a timestamp and check this on the server as long as the clocks are in sync, but I’d prefer to check the connection to see if it is still open as well).

Is what I’m trying to do possible, and if so, how?

I don’t think so. FIN does not mean the connection is broken. It is perfectly valid that A sends B some data, followed by FIN; then A continues to read from B. Nothing wrong with this half-closed state.

Your better choice is to improve server throughput so that clients don’t have to wait so long.

Java how to handle HTTP GET request after, If you just want a Java-based web server which handles HTTP requests for you then you should look at Tomcat, which will look after things like returning static files automatically, and will also allow you to define Java code to provide custom responses to specific requests.

Читайте также:  Отобразить имя пользователя php

Checking Content-Type of HTTP POST Request to Java servlet

I’ve written a simple servlet that accepts HTTP POST requests and sends back a short response. Here’s the code for the servlet:

import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.*; /** * Servlet implementation class MapleTAServlet */ @WebServlet(description = "Receives XML request text containing grade data and returns response in XML", urlPatterns = < "/MapleTAServlet" >) public class MapleTAServlet extends HttpServlet < private static final long serialVersionUID = 1L; private Log log = LogFactory.getLog(MapleTAServlet.class); /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < String strXMLResponse = ""; String strMessage = ""; int intCode = 0; ServletOutputStream stream = null; BufferedInputStream buffer = null; try < String strContentType = request.getContentType(); // Make sure that the incoming request is XML data, otherwise throw up a red flag if (strContentType != "text/xml") < strMessage = "Incorrect MIME type"; >else < intCode = 1; >// end if strXMLResponse += intCode + "" + strMessage + ""; response.setContentType("text/xml"); response.setContentLength(strXMLResponse.length()); int intReadBytes = 0; stream = response.getOutputStream(); // Converts the XML string to an input stream of a byte array ByteArrayInputStream bs = new ByteArrayInputStream(strXMLResponse.getBytes()); buffer = new BufferedInputStream(bs); while ((intReadBytes = buffer.read()) != -1) < stream.write(intReadBytes); >// end while > catch (IOException e) < log.error(e.getMessage()); >catch (Exception e) < log.error(e.getMessage()); >finally < stream.close(); buffer.close(); >// end try-catch > > 

And here’s the client that I’m using to send the request:

import java.net.HttpURLConnection; import java.net.URL; import java.io.*; public class TestClient < /** * @param args */ public static void main(String[] args) < BufferedReader inStream = null; try < // Connect to servlet URL url = new URL("http://localhost/mapleta/mtaservlet"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Initialize the connection conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); conn.setUseCaches(false); conn.setRequestProperty("Content-Type", "text/xml"); //conn.setRequestProperty("Connection", "Keep-Alive"); conn.connect(); OutputStream out = conn.getOutputStream(); inStream = new BufferedReader(new InputStreamReader(conn.getInputStream())); String strXMLRequest = ""; out.write(strXMLRequest.getBytes()); out.flush(); out.close(); String strServerResponse = ""; System.out.println("Server says: "); while ((strServerResponse = inStream.readLine()) != null) < System.out.println(strServerResponse); >// end while inStream.close(); > catch (IOException e) < e.printStackTrace(); >catch (Exception e) < e.printStackTrace(); >// end try catch > > 

The issue I’m having is that when I run the client program, I’m getting the following output:

Server says: 0Incorrect MIME type 

I’ve tried calling request.getContentType() and have gotten «text/xml» as the output. Just trying to figure out why the string isn’t matching up.

You’re comparing strings the wrong way.

if (strContentType != "text/xml") 

Strings are not primitives, they are objects. When using != to compare two objects, it will only test if they do not point to the same reference . However, you’re rather interested in comparing the content of two different string references, not if they point to the same reference.

You should then use the equals() method for this:

if (!strContentType.equals("text/xml")) 

Or, better, to avoid NullPointerException if the Content-Type header is not present (and thus becomes null ):

if (!"text/xml".equals(strContentType)) 

Http Basic Authentication in Java using HttpClient?, I am trying to mimic the functionality of this curl command in Java: Connect and share knowledge within a single location that is structured and easy to search. but end with «\r\n», then server will return «bad request». Also following code is working as well,

Читайте также:  Максимальный элемент вектора python

Источник

How to Test Java HTTP Client Usages (e.g. OkHttp, Apache HttpClient)

Fetching data via HTTP from a remote system is a task almost every application has to solve. Fortunately, there are mature Java HTTP client libraries available that are robust and have a user-friendly API. Most of the frameworks ship their own HTTP client (e.g Spring with WebClient and RestTemplate , Jakarta EE with the JAX-RS Client), but there are also standalone clients available: OkHttp, Apache HttpClient, Unirest, etc. When it comes to testing Java classes that use one of these clients, I often see developers trying to mock the internals of the library. With this article, you’ll understand why such an approach is not beneficial and what you should do instead when writing a test that involves a Java HTTP client.

Why Plain Old Unit Tests Are Not Enough

Most of the Java HTTP clients are instantiated with static methods. In addition, we usually chain multiple method calls or use a builder to construct the instance of the client or the HTTP request.

Even though Mockito is able to mock static method calls and with deep mocking, we could keep the stubbing setup lean, we should always remember:

Every time a mock returns a mock a fairy dies.

We end up in a mocking hell and have to mock the whole setup. With this approach, we also almost duplicate our production code as the stubbing setup has to match our usage.

While we could test conditionals e.g. behavior on non 200 HTTP responses or how our implementation handles exceptions, there is not much benefit with this approach.

A better solution for testing our Java HTTP clients would be to actually test them in action and see how they behave to different responses. This also allows us to test more niche scenarios like slow responses, different HTTP status codes, etc.

A Better Approach for Testing HTTP Clients

Instead of heavy lifting with Mockito, we’ll spawn a local web server and queue HTTP responses. We can then let our HTTP clients connect to this local server and test our code.

Whether or not we are still writing a unit test depends on your definition and scope. However, we are still testing a unit of our application in isolation. Going further, we also have to take a small overhead (time-wise) into account. Most of the time this is negligible.

The two most common libraries for this are WireMock and the MockWebServer from OkHttp. We’ll use the lightweight MockWebServer for this demo, but you can achieve the same with WireMock.

There’s already an example on how to use WireMock with JUnit 5 for testing a Spring Boot application on my blog: Spring Boot Integration Tests with WireMock and JUnit 5

We include the MockWebServer with the following Maven import:

Источник

Оцените статью