I'm creating a soap client using apache cxf.I used a network hook capture the data and find out in Http header SOAPAction is empty
SOAPAction : ""
Below is the code
URL wsdlurl=SOAPWebServiceTransport.class.getClassLoader().
getResource("my.wsdl");
OnlinePort service= new OnlinePortService(wsdlurl).getOnlinePortPort();
Client proxy = ClientProxy.getClient(service);
// Provides WS-Security
WSS4JOutInterceptor wss4jOut = new WSS4JOutInterceptor();
wss4jOut.setProperty("action", "UsernameToken");
wss4jOut.setProperty("user", userName);
wss4jOut.setProperty("passwordType", "PasswordText");
wss4jOut.setProperty("password", password);
wss4jOut.setProperty(WSHandlerConstants.ADD_UT_ELEMENTS,
WSConstants.NONCE_LN + " " + WSConstants.CREATED_LN);
wss4jOut.setProperty(WSHandlerConstants.PW_CALLBACK_CLASS, ServerPasswordCallback.class.getName());
proxy.getEndpoint().getOutInterceptors().add(wss4jOut);
setConduitProperties((HTTPConduit) proxy.getConduit(),url);
In the setConduitProperties I'm just setting some http properties.
While investigating this issue I found a work around
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("SOAPAction", Arrays.asList("myPrefix:mySoapMethod"));
proxy.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
But the problem is that if I have more than one method then in the Http header its putting all the method
SOAPAction : "myPrefix:mySoapMethod,myPrefix:mySoapMethod2"
Is there any better solution to handle this?
I would suggest to set the SOAPAction header per request. Otherwise, the server is not be able to tell which method do you want to invoke.
Related
I'm using jersey-client 1.19.4 to test my web application.
If I test with postman, I can find the cookie "JSESSIONID" after 'send' action. And I can find 'jsessionid=...' in ClientResponse.toString(), But ClientResponse.getCookies() returns nothing.
WebResource webResource = client.resource(someUrl);
FormDataMultiPart formData = new FormDataMultiPart();
formData.bodyPart(new FormDataBodyPart("userId", userId));
formData.bodyPart(new FormDataBodyPart("uPasswd", uPasswd));
ClientResponse response = webResource.accept("*/*").type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, formData);
System.out.println("response: " + response.toString()); // 'jsessionid' found here
List<NewCookie> cookies = response.getCookies();
System.out.println("# of cookies: " + cookies.size()); // prints "# of cookies: 0"
How can I get "JSESSIONID" from ClientResponse?
JSESSIONID can be set in few different ways. As per
JSR-000315 Java Servlet 3.0 Final Release, chapter 7.1 Session Tracking Mechanisms, following can be used:
Cookies
SSL Sessions
URL Rewriting
In your case it appears that URL Rewriting is being used. The two most common reasons being:
The server is configured not to issue cookies
Your client doesn't support cookies
Since you get the cookie while using Postman it most likely means that your Jersey Client doesn't handle cookies. One way to integrate it with Apache HttpClient using jersey-apache-client as per this answer.
From the mailing list:
http://jersey.576304.n2.nabble.com/Session-Handling-not-working-with-Jersey-Client-td4519663.html
The Jersey client by default uses HttpURLConnection that does not
support cookie management (and thus sessions).
You need to switch to using the Apache HTTP client support.
Then set the following property to true: PROPERTY_HANDLE_COOKIES
DefaultApacheHttpClientConfig config = new
DefaultApacheHttpClientConfig(); config
.setProperty("com.sun.jersey.impl.client.httpclient.handleCookies",
true);
ApacheHttpClient c = ApacheHttpClient.create(config);
Plus you can also use authorization with the Apache HTTP client
integration.
DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig();
config.getState().setCredentials(null, null, -1, "foo", "bar");
ApacheHttpClient c = ApacheHttpClient.create(config);
WebResource r = c.resource("http://host/base");
String s = r.get(String.class);
s = r.post(String.class, s);
I've created a set of proxy classes in NetBeans for a SOAP web service.
I'd like to add an HTTP header to the outgoing request.
Map<String, Object> requestHeaders = new HashMap<>();
requestHeaders.put("X-Header", header);
AccountManagementService service = new AccountManagementService();
AccountManagementServiceSoap soap = service.getAccountManagementServiceSoap();
GetMembershipSummaryResponse.GetMembershipSummaryResult membershipSummary = soap.getMembershipSummary("mikeb#foobar.com");
I saw a bunch of JAX-WS header examples for when you are getting the individual port from the service. Is there an easier way? Can I just add the header to some collection on service or soap object?
after some digging I found this post: jax-ws change Content-type to Content-Type because server is hyper sensitive
which isn't really a full answer, so I am going to post the full answer here:
AccountManagementService service = new AccountManagementService();
AccountManagementServiceSoap soap = service.getAccountManagementServiceSoap();
((BindingProvider)soap).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS,
Collections.singletonMap("X-Header",Collections.singletonList(header)));
GetMembershipSummaryResponse.GetMembershipSummaryResult membershipSummary = soap.getMembershipSummary("mikeb#foobar.com");
I am using Apache HTTP Client Library to send HTTP request. I have following questions:
1- Does this library attaches any default headers to the request, or you have to attach all the headers yourself.
HttpClient client = new HttpClient();;
HttGet request = new HttpGet('http://www.example.com');
//Now Can i execute the request directly or do i need to
//add headers before executing the request
client.execute(request);
2- I also want to see the headers that are being sent to the server. I tried "request.getHeaders()" but it just prints - "[Lorg.apache.http.Header;#1bc2616". How can I get it to print headers in a name - value format.
What version of Apache HttpClient are you using? In version 4.0.1 there is a method HttpGet#getAllHeaders() which returns an array of Header object. See grep code here - http://grepcode.com/file/repo1.maven.org/maven2/org.apache.httpcomponents/httpcore/4.0.1/org/apache/http/message/AbstractHttpMessage.java#AbstractHttpMessage.getAllHeaders%28%29
I tried running this code:
final HttpClient client = new DefaultHttpClient();
final HttpGet get = new HttpGet("http://www.google.com");
client.execute(get);
for (final Header header : get.getAllHeaders()) {
System.out.println("Header: " + header.getName() + " = " + header.getValue());
}
System.out.println(get.getAllHeaders().length);
I did not see any headers getting printed in the console and get.getAllHeaders().length returned zero (0). So I would assume that HttpClient doesn't provide any default Headers.
I wouldn't recommend to use separate HttpGet/HttpPost/HttpPut
but HttpRequest Interface. There you'll be able to set Header/body as HttpEntity.
But Default header is attached:
method: GET/POST/PUT by default;
You should separately set Content-Type and Encoding
is it possible to pass some data in HTTP Header, while redirecting a request from one server to another.
Here is my scenario,
I have one generic filter, via which every request is passing.
Now, based on some condition, I'm redirecting the request to some different server using the API objHttpServletResponse.sendRedirect(strURL).
But, the issue is, when I'm setting some data in response header like objHttpServletResponse.setHeader("Key", "Value"); That's not available in the redirected server.
So, my questions are,
1. Is there any way to pass some data in header while redirecting a request?
2. If not, what are the other possible ways to send some data while redirecting a request?
Please Note: few other ways, like
using URL parameters:
objHttpServletResponse.sendRedirect(strURL+"?param="+ strParamValue);
or
using session:
HttpSession session = httpRequest.getSession();
session.setAttribute("Key", "Value");
is not what I'm expecting.
The headers you set are written to the response that gets sent to the client, along with a Location header and a status code. See Redirecting a request using servlets and the "setHeader" method not working
The client is then supposed to send an identical request to the URL you specified in the Location header. Identical to the request it sent to you.
You want the browser to send a header you specify along with the redirected request. Have you considered adding a (domain) Cookie header? Some googling leads me to believe that cookies set in a redirect response will get picked up by most browsers. See http://blog.dubbelboer.com/2012/11/25/302-cookie.html
Please have a look at Apache HttpClient.
This example adds several parameters to the post request :
String url = "https://selfsolve.apple.com/wcResults.do";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("sn", "C02G8416DRJM"));
urlParameters.add(new BasicNameValuePair("cn", ""));
urlParameters.add(new BasicNameValuePair("locale", ""));
urlParameters.add(new BasicNameValuePair("caller", ""));
urlParameters.add(new BasicNameValuePair("num", "12345"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
The problem is that the redirect() method of the response initiates a new request altogether, thereby loosing the attributes that were set before redirecting. Luckily there is a fluent way of solving the problem still.
response.setHeader("Key", "Value");
request.getRequestDispatcher("redirecturl").forward(request, response);
Then in your destination you can do
response.getHeaders("key")
You can use JS redirect, i.e. instead of calling sendRedirect return HTML page with embedded javascript that will do redirect setting headers you need.
However, using GET parameters is really the best solution. If you have concerns about users altering parameters manually - use MAC code to protect parameters.See
Message authentication code
In simplest form, ?p1=1&p2=2&mac={mac value}, where {mac value} = md5('MY_SECRET_KEY' + 'p1=1&p2=2').
Receiving side can recalculate MAC and compare it with provided one. Since external users can not know 'MY_SECRET_KEY', they will not be able to make valid MAC.
Have you checked the HTTP request/response from/to server? You can use a number of plugins on chrome or firefox to check that. You would be able to see if value is being passed from your server to another server or not
Also retrieve the header using httpResponse.getHeader("Key"); not using request.getHeader("key"). One of my colleague was facing same issue some days back, he was using request to fetch header values
Using Jersey in Java I have a response object
Client c=Client.create();
WebResource r = c.resource("http://example.com/path");
MultivaluedMap<String, String> params = new MultivaluedMapImpl();
params.add("param1", value);
r=r.path(getQualifiersByPromoServicePath).queryParams(params);
ClientResponse response = r.accept(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
How can I get the url used to make the request? (for debug purposes)
i.e. i want to get the string "http://example.com/path?param1=value" ?
Have you tried r.getURI();? Should be what you're looking for...
Use a Logging Filter and direct it's output to System.out for debugging purposes.
Right after instantiating your client add the following line:
c.addFilter(new LoggingFilter(System.out));