I have requirement to post a soap xml to a POST endpoint. But before posting, I need to do a health check of that url or find the status of that url. I tried to do an HttpURLConnection 'GET' method, but the url does not support 'GET'. Please help!
As you said yourself in the question that method is POST and not GET. So sending a GET request is irrelevant (regardless of whether it works or not). You can send a POST request using HttpURLConnection. But you will have to read and learn how to properly do it. The lazy way is to use a 3d party HttpClient. Here are a few options:
Apache HttpClient - a very widely used library
OK HttpClient - Open Source library
And my favorite (Open Source library written by me) MgntUtils library
With MgntUtils library your code could be as simple as
private static void testHttpClient() {
HttpClient client = new HttpClient();
client.setContentType("application/json; charset=utf-8");
client.setConnectionUrl("http://www.your.url.com/");
String content = null;
try {
content = client.sendHttpRequest(HttpMethod.POST);
} catch (IOException e) {
content = TextUtils.getStacktrace(e, false);
}
System.out.println(content);
}
Here is Javadoc for MgntUtils HTTPClient class. The library itself could be found here as Maven artifacts or on Git (including sources and JavaDoc). An article about the library (although it doesn't describe HttpClient feature) could be found here
Related
We are making use of this end point - https://www.googleapis.com/oauth2/v4/token
to get the access token.
We make use of apace HTTP classes to make a POST request to this end point in this way -
HttpPost httpPost = new HttpPost(GET_ACCESS_TOKEN_API);
StringBuilder blr = new StringBuilder().append(CLIENT_ID).append("=")
.append((String) accountCredentials.get(CLIENT_ID)).append("&")
.append(CLIENT_SECRET).append("=")
.append((String) accountCredentials.get(CLIENT_SECRET))
.append("&").append(REFRESH_TOKEN).append("=")
.append((String) accountCredentials.get(REFRESH_TOKEN))
.append("&grant_type=refresh_token")
.append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
// The message we are going to post
StringEntity requestBody = new StringEntity(blr.toString());
// the default content-type sent to the server is
// application/x-www-form-urlencoded.
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
// Make the request
HttpResponse response = HttpUtils.getHttpClient().execute(httpPost);
There has been a recent intimation from google to migrate from out-of-band as they have plans to deprecate this.
We make use of it this way as you can see in the code above -append("&redirect_uri=urn:ietf:wg:oauth:2.0:oob");
GET_ACCESS_TOKEN_API is https://www.googleapis.com/oauth2/v4/token.
I saw some posts mentioning that we have to replace this redirect_uri to localhost.
Can someone explain exactly how this works and what change needs to be done to migrate this successfully ? I tried searching through the documentation to see if there any sample examples but couldn't find anything that matches our use case.
I am referring to this site -
https://developers.google.com/api-client-library/java/google-oauth-java-client/support
I tried to browse through samples, guides, but it mostly talks about different API's. I didn't find the github links that much useful.
Any help would be much appreciated.
I am trying to consume a RESTFUL web service using Java(HttpURLConnection and InputStream).I am able to print the response using BufferedReader, but it returns a response header as well and the format is causing issues to convert it to a Java POJO.
I tried using a URLConnection and then retrieving the input stream and passing it to the ObjectMapping(provided by Jackson)
final URL url = new URL("url");
final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
uc.setRequestMethod("GET");
final ObjectMapper objectMapper = new ObjectMapper();
MyData myData = objectMapper.readValue(uc.getInputStream(), MyData.class);
Error Message : "No content to map due to end-of-input\n"
In your code you don't show where you actually read the data and where you declared and filled your output variable. As code is now it seems to be the incorrect reading from your rest service. But instead of writing your own code to read fro rest url I would suggest to use the 3d party library that does it for you. Here is few suggestions: Apache Http Client, OK Http client and finally my favorite - MgntUtils Http Client (library written and maintained by me) Here is the HttpClient javadoc, Here is the link to The latest Maven artifacts for MgntUtils library and here MgntUtils Github link that contains library itself with sources and javadoc. Choose some Http Client and read the content using that client and then you can use the content.
I've successfully managed to logon to a site using httpclient and print out the cookies that enable that logon.
However, I am now stuck because I wanted to display subsequent pages in a JEditorPane using .setPage(url) function. However, when I do that and analyse my GET request using Wireshark I see that the user agent is not my httpclient but the following:
User-Agent: Java/1.6.0_17
The GET request (which is coded somewhere in side jeditorpane's setPage(URL url) method) does not have the cookies that were retrieved using the httpclient. My question is - how can I somehow transfer the cookies received with httpclient so that my JEditorPane can display URLs from the site?
I'm beginning to think it's not possible and I should try and logon using normal Java URLconnection etc but would rather stick with httpclient as it's more flexible (I think). Presumably I would still have a problem with the cookies??
I had thought of extending the JEditorPane class and overriding the setPage() but I don't know the actual code I should put in it as can't seem to find out how setPage() actually works.
Any help/suggestions would be greatly appreciated.
Dave
As I mentioned in the comment, HttpClient and the URLConnection used by the JEditorPane to fetch the URL content don't talk to each other. So, any cookies that HttpClient may have fetched won't transfer over to the URLConnection. However, you can subclass JEditorPane like so :
final HttpClient httpClient = new DefaultHttpClient();
/* initialize httpClient and fetch your login page to get the cookies */
JEditorPane myPane = new JEditorPane() {
protected InputStream getStream(URL url) throws IOException {
HttpGet httpget = new HttpGet(url.toExternalForm());
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
// important! by overriding getStream you're responsible for setting content type!
setContentType(entity.getContentType().getValue());
// another thing that you're now responsible for... this will be used to resolve
// the images and other relative references. also beware whether it needs to be a url or string
getDocument().putProperty(Document.StreamDescriptionProperty, url);
// using commons-io here to take care of some of the more annoying aspects of InputStream
InputStream content = entity.getContent();
try {
return new ByteArrayInputStream(IOUtils.toByteArray(content));
}
catch(RuntimeException e) {
httpget.abort(); // per example in HttpClient, abort needs to be called on unexpected exceptions
throw e;
}
finally {
IOUtils.closeQuietly(content);
}
}
};
// now you can do this!
myPane.setPage(new URL("http://www.google.com/"));
By making this change, you'll be using HttpClient to fetch the URL content for your JEditorPane. Be sure to read the JavaDoc here http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JEditorPane.html#getStream(java.net.URL) to make sure that you catch all the corner cases. I think I've got most of them sorted, but I'm not an expert.
Of course, you can change around the HttpClient part of the code to avoid loading the response into memory first, but this is the most concise way. And since you're going to be loading it up into an editor, it will all be in memory at some point. ;)
Under Java 5 & 6, there is a default cookie manager which "automatically" supports HttpURLConnection, the type of connection JEditorPane uses by default.
Based on this blog entry, if you write something like
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);
CookieHandler.setDefault(manager);
seems enough to support cookies in JEditorPane.
Make sure to add this code before any internet communication with JEditorPane takes place.
How can I upload file to a server (API interface) in Java, just like the .NET programmers do in C#:
cli.UploadFileAsync(URL, filename);
Tried to do findout a way by using HttpClient but no success.
I believe async http client is what you are looking for. Read through the docs and I am sure you can find your way.
AsyncHttpClient client = new AsyncHttpClient();
Response response =
client.preparePut(("http://sonatype.com/myFile.avi").execute();
Another blog explaining its usage: http://jfarcand.wordpress.com/2010/12/21/going-asynchronous-using-asynchttpclient-the-basic/
Does anyone have a good example of how to do https over http (or a socket)?
The embedded java platform doesn't support https out of the box, but I'm sure it should be possible using some 3rd party libraries or source code snippets.
If anyone can point me to the correct direction I'd be very grateful
What profile are you using? MIDP comes with HTTS handler. I just checked the code. This package,
com.sun.midp.io.j2me.https
implements HttpsConnection interface.
EDIT:
I think your best bet is to find an old version of BouncyCastle JCE that works with your version of Java. BC JCE comes with this class to handle SSL,
http://www.bouncycastle.org/docs/docs1.3/org/bouncycastle/crypto/tls/TlsProtocolHandler.html
This test shows you how to make a simple HTTPS request.
http://www.java2s.com/Open-Source/Java-Document/Security/Bouncy-Castle/org/bouncycastle/crypto/tls/test/BasicTlsTest.java.htm
As bitover has said, you can use apache http components.
Simple example where https page need user credentials:
public static void main (String[] args){
HttpClient httpclient = new DefaultHttpClient();
// Note that the specified port 443 corresponds with the SSL service
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new AuthScope("www.moneytrackin.com", 443),
new UsernamePasswordCredentials("user", "password"));
// Https page to access
HttpGet httpget = new HttpGet("https://www.moneytrackin.com/api/rest/getBalance");
HttpResponse response;
try {
response = httpclient.execute(httpget);
System.out.println("State: "+response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
System.out.println("Data: "+result);
instream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
More examples in this blog.
Apache HttpCore is what you need. See more: http://hc.apache.org/httpcomponents-core/index.html
Br,
Gabi
From what i can remember, with HttpComponents you just set the socket factory to use the SSLSocketFactory and it works; however, the SSLSocketFactory was added in Java 1.4.
Honestly, I would not think the Apache HttpComponents API would even work on the limited environment you described... you would most likely need an older version, from back when it was called HttpClient (I think) and part of the Jakarta Commons.
Good luck
JBoss netty has an example of HTTP client, you just need to add the SSlHandler in HTTPRequestHandler and HTTPResponseHandler.