Jersey client not following redirects? - java

I am struggling to get a Jersey client that follows redirects, even though "I know I had this working earlier." (Haven't looked at the code in a while).
I thought had a complex case where it was failing when the redirect was from HTTP to HTTPS. But I cannot get even this simple test below to run:
package com.soliantconsulting.jira.test;
import static org.junit.Assert.*;
import com.sun.jersey.api.client.*;
import org.junit.Test;
public class JerseyClientTest {
public void test() {
Client c = Client.create();
c.setFollowRedirects( true );
WebResource r = c.resource("http://www.yahoo.com");
String response = r.get(String.class);
System.out.println( response );
}
}
When run, this code throws:
com.sun.jersey.api.client.UniformInterfaceException: GET http://www.yahoo.com returned a response status of 301 Moved Permanently
I've tried a couple different flavors of setting the redirect-follow option, so I must be doing something fundamentally wrong, I think.
Mac OS 10.9.4, JDK 1.7.0_65, Jersey 1.18.1, Eclipse Luna, Maven 3.2.3.

Related

Wildfly 26 changed behaviour of REST with content type "x-www-form-urlencoded"

while updating from Wildfly version 24 to version 26 I found an anoying change within REST.
If I post with curl some data, it is just not received on the server. I already found out, that this is because of default content type "x-www-form-urlencoded", used by curl.
Example server code:
import java.io.IOException;
import java.io.InputStream;
import javax.ejb.Stateless;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
#Stateless
#Path("test")
public class RestSample {
#POST
#Path("t1")
public Response postData(InputStream dataInputStream) {
String content=null;
try {
content=IOUtils.toString(dataInputStream,"UTF-8");
System.out.println("content length: "+content.length());
System.out.println("content: "+content);
} catch(IOException e) {
System.out.println("An exception occurred."+e);
}
return Response.status(Response.Status.ACCEPTED).entity("Received: "+content).build();
}
#POST
#Path("t2")
public String postData(String input) {
return "Received: "+input;
}
}
Both methods postData() do the same and react the same. The first one is working more low level with InputStream and Response, but we can focus on the second one, which is really simple: The received content becomes part of the response.
If I do start my Wildfly 24 and do the call:
curl -d "Hello World" http://localhost/server/rest/test/t2
I see the response:
Received: Hello World
The same if I call:
curl -d "Hello World" -H 'Content-Type: application/xml' http://localhost/server/rest/test/t2
I see the response:
Received: Hello World
But if I use the same code within Wildfly 26, the behaviour changes:
curl -d "Hello World" -H 'Content-Type: application/xml' http://localhost/server/rest/test/t2
This still works and returns:
Received: Hello World
But:
curl -d "Hello World" http://localhost/server/rest/test/t2
Now gets an empty input stream or empty string and I just get:
Received:
So, the question is:
What has changed? Is ther a chance to get back the old behaviour?
Update:
This is really strange! I apologize for not testing my code on a ‘clear’ Wildfly! As James mentioned: There it is working, but I did simply not expect such side effects!
I compared my productive system with the clear test system a long time and compared e. g.
standalone.xml
modules folder
web.xml
application.xml
adding primefaces-11.0.1.jar
And I only found out one thing: If I remove the <login-config> section from my web.xml in my productive software, the problem is away. But if I put this section within my clean test system, it still works!
So it looks like the problem is based on multiple components but I do not find anything else. So, I found a workaround for the <login-config> section and hope there are no other problems from the same source.

How to enable cookies while sending a request with Java Jersey client?

I need to send a get request to an API and get the results. I am using Java, Jersey library in my project and I decided to use Jersey client in order to get the data. However, the API returns an error message which indicates that I should enable cookies to reach out this API. I can get correct response when try with applications like postman, or just with using a normal browser like chrome. But I could not find out how can I enable cookies in Java Jersey client object.
I searched to learn how to enable cookies in a Java Jersey client but I could not find any resource about it. So I could not try any solution.
My code is very simple:
Client client = Client.create(); // Create jerseu client
WebResource webResource = client.resource(BASEURI + EXCHANGEINFO); // create web resource with a specific URI
System.out.println(webResource
.accept("application/json")
.get(ClientResponse.class)
.getEntity(String.class)); // Write results to console
At the result of this request, I got the error that I mentioned above. How can I enable cookies while sending a request with Java Jersey client?
As per the discussion, I have gone through the api you have provided. Actually, the api provides a misleading message while making rest call. If you look into the details of the error message which is received from the api call, it says.
The owner of this website (api.pro.coinbase.com) has banned your
access based on your browser's signature (4e0a3c06895d89af-ua21).
So what is the answer ? The api actually wants that the call should be made from browser and each browser sends a header called "User-Agent". See what is user agent. However, I have solved your problem, you can check the complete code below.
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class TestGetCallByJersey {
public static void main(String[] args) {
String resourceUri = "https://api.pro.coinbase.com/products";
try {
Client client = Client.create();
WebResource webResource = client.resource(resourceUri);
ClientResponse response =
webResource
.accept("application/json")
.header("User-Agent", "Mozilla/5.0")
.get(ClientResponse.class);
System.out.println("response status = " + response.getStatus());
String result = response.getEntity(String.class);
System.out.println("Output from api call .... \n" + result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Currently, I have tested in Java 8 and I used the following jar file.
jersey-client version 1.8
If you are using, Maven, you can include the following dependency in pom.xml.
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>

Extract data from soap service using java code

i am tring to extract response data from wsdl url using soapui java code. all are working good, but problem is in response.
in response i am getting ? instead of getting proper data.
Eclipse Console result
but when i am tring to hit wsdl url using soapui it is working fine.
check my code
package src.com;
import com.eviware.soapui.impl.wsdl.WsdlInterface;
import com.eviware.soapui.impl.wsdl.WsdlOperation;
import com.eviware.soapui.impl.wsdl.WsdlProject;
import com.eviware.soapui.impl.wsdl.support.wsdl.WsdlImporter;
import com.eviware.soapui.model.iface.Operation;
public class Test {
public static void main(String[] args) throws Exception {
WsdlProject project = new WsdlProject();
WsdlInterface[] wsdls = WsdlImporter.importWsdl(project, "http://localhost:8080/SoapService/services/TestService?wsdl");
WsdlInterface wsdl = wsdls[0];
for (Operation operation : wsdl.getOperationList()) {
WsdlOperation wsdlOperation = (WsdlOperation) operation;
System.out.println("Request:\n"+wsdlOperation.createRequest(true));
System.out.println("\nResponse:\n"+wsdlOperation.createResponse(true));
}
}
}
Check Jars
Within the SoapUI application you are actually making a call out to the web service and getting a response. In your sample java code you are just generating a response XML from the WSDL file instead of actually calling out to the web service and it's defaulting any required values to have a ?. If you generate the same response within the SoapUI application you will see the same ? set for the findAllReturned element.
You can use the java SoapUI's WSDLSubmit class to make a call out to the web service and get a response back.
The answer to this linked question shows a code sample of how you would go about making an actual call out to the web service using the SoapUI java api:
https://stackoverflow.com/a/14814524/8127149
And this link has other examples of using the WSDLSubmit class:
http://www.programcreek.com/java-api-examples/index.php?api=com.eviware.soapui.impl.wsdl.WsdlSubmit

SSLPeerUnverifiedException:"peer not authenticated" while using groovy's RestClient with ignoreSSLIssues()

I am writing an integration test for my Rest end point and I have choosen groovy's RestClient. My rest call is on "HTTPS" and I started facing SSL exceptions.
While digging more into this, I was happy to know about ignoreSSLIssues() method (http://groovy.codehaus.org/modules/http-builder/doc/ssl.html). As this is available in 0.7.1 version of HttpBuilder, I upgraded this jar and some dependent jars as well. So with this in place, as per the doc, i was hoping the below code to work -
def httpBuilder = new HTTPBuilder('baseurl')
httpBuilder.ignoreSSLIssues()
def resp = httpBuilder.get(path : 'restPath')
println resp
But this is still throwing javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated.
Any help on this is appreciated.
Thanks.
Just ran into this issue. You also get this deceptive error if you use an outbound proxy and haven't configured the HTTPBuilder class to use it explicitly.
You need to set the setProxy() method of HTTPBuilder. JVM OPTS such as -Dhttp.proxyHost do not seem to be respected by HTTPBuilder for whatever reason. My version looks something like this:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.HEAD
def http = new HTTPBuilder( 'https://www.dev.java.net/' )
http.setProxy("my.proxy.com", 8080, "http")
http.ignoreSSLIssues()
def status = http.request( HEAD ) {
response.success = { it.status }
}

JAX-WS WebService Client - Streaming large attachements - different behavior, depending on JRE version

I created a WebService client from a provided WSDL-File, using the already in the JRE bundled JAX-WS API.
I generated the proxy classes with the wsimport tool of JDK6 Update 37.
The client should be able to download large files/data, using MTOM and streaming.
I followed the instructions provided in the Metro user guide.
The proxy method I'm calling returns a DateHandler object.
package de.christopherhuebner.webservicetest.client;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import javax.activation.DataHandler;
import javax.xml.namespace.QName;
import de.christopherhuebner.webservicetest.ImageServer;
import de.christopherhuebner.webservicetest.ImageServerService;
public class ImageServiceClient {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/ImageWebService?wsdl");
QName qname = new QName("http://webservicetest.christopherhuebner.de/", "ImageServerService");
ImageServerService is = new ImageServerService(url, qname);
MTOMFeature mtom = new MTOMFeature();
StreamingAttachmentFeature stf = new StreamingAttachmentFeature(null, true, 4000000L);
ImageServer port = is.getImageServerPort(mtom, stf);
DataHandler dh = port.getImage();
System.out.println("Java-Version: " + System.getProperty("java.version"));
System.out.println("DataHandler: " + dh.getClass());
System.out.println("DataSource: " + dh.getDataSource().getClass());
OutputStream out = new FileOutputStream("test.jpg");
dh.writeTo(out);
out.close();
}
}
When running this code with JRE6, the following output is printed to the console:
Java-Version: 1.6.0_37
DataHandler: class javax.activation.DataHandler
DataSource: class com.sun.istack.internal.ByteArrayDataSource
Unfortunately there is no streaming possible, as the ByteArrayDataSource is filled in the clients memory which causes an OutOfMemoryException when receiving data larger than the max heap size. When I dare to cast this DataHandler to a StreamingDataHandler as suggested in the already mentioned user guide, a ClassCastException is thrown.
When running the client with JRE7, everything is fine, as described in the user guide:
Java-Version: 1.7.0_10
DataHandler: class com.sun.xml.internal.ws.encoding.MIMEPartStreamingDataHandler
DataSource: class com.sun.xml.internal.ws.encoding.MIMEPartStreamingDataHandler$StreamingDataSource
Is there any possibility to get a StreamingDataHandler back, when using JRE6?
Or am I really forced to use a newer JAX-WS RI version (Metro, which seems to be included in the JRE) via the -Djava.endorsed.dirs=path_to_newer_jaxws_libs mechanism?
When are the temp files, which are generated during streaming (MIMExxxxx.tmp, see StreamingAttachmentFeature for configuration), deleted?

Categories