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/
Related
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
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'm using AsyncHttpClient library to make HTTP requests from a very basic Android app. For now, I just need to make a POST request with a JSON body (and that's a mandatory constraint, since the REST services I have to use expect a request in that format) containing a username and a password.
Not knowing much about Android development and the library in question I tried to make a simple GET request to Google, and it perfectly worked. Then, I tried to switch to a POST request but it seems from the documentation that the post method needs strictly a RequestParams parameter.
I really need to send a JSON: is there a way to do so with AsyncHttpClient? I tried several solutions found both on the web and on StackOverflow, but unfortunately no one worked.
Ultimately, as a last chance, I'm willing to switch library (and suggestions in this direction would be welcome, too - at least if they're easy-to-use as AsyncHttpClient is, considering my inexperience), but I would prefer to stick to my current choice.
Thanks for your help.
first, i suggest u to use retrofit library, it's simple, useful and sweet
but for now, we should to know that how do you do your post,
for example, do you test this:
private static AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("param1", "Test");
client.post(Url, params, responseHandler);
JSONObject jsonParams = new JSONObject();
jsonParams.put("param1", "Test");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, Url, entity, "application/json",responseHandler);
I am decoding http packets.
And I faced a problem that chunk problem.
When I get a http packet it has a header and body.
When transefer-encoding is chunked I don't know what to do ?
Is there a useful API or class for dechunk the data in JAVA ?
And if someone , experienced about http decoding , please show me a way how to do this ?
Use a fullworthy HTTP client like Apache HttpComponents Client or just the Java SE provided java.net.URLConnection (mini tutorial here). Both handles it fully transparently and gives you a "normal" InputStream back. HttpClient in turn also comes with a ChunkedInputStream which you just have to decorate your InputStream with.
If you really insist in homegrowing a library for this, then I'd suggest to create a class like ChunkedInputStream extends InputStream and write logic accordingly. You can find more detail how to parse it in this Wikipedia article.
Apache HttpComponents
Oh, and if we are talking about the client side, HttpUrlConnection does this as well.
If you are looking for a simple API try Jodd Http library (http://jodd.org/doc/http.html).
It handles Chunked transfer encoding for you and you get the whole body as a string back.
From the docs:
HttpRequest httpRequest = HttpRequest.get("http://jodd.org");
HttpResponse response = httpRequest.send();
System.out.println(response);
Here is quick-and-dirty alternative that requires no dependency except Oracle JRE:
private static byte[] unchunk(byte[] content) throws IOException {
ByteArrayInputStream bais = new ByteArrayInputStream(content);
ChunkedInputStream cis = new ChunkedInputStream(bais, new HttpClient() {}, null);
return readFully(cis);
}
It uses the same sun.net.www.http.ChunkedInputStream as java.net.HttpURLConnection does behind the scene.
This implementation doesn't provide detailed exceptions (line numbers) on wrong content format.
It works with Java 8 but could fail in with next release. You've been warned.
Could be useful for prototyping though.
You can choose any readFully implementation from Convert InputStream to byte array in Java.
Sorry, I'm quite new to Java.
I've stumbled across HttpGet and HttpPost which seem to be perfect for my needs, but a little long winded. I have written a rather bad wrapper class, but does anyone know of where to get a better one?
Ideally, I'd be able to do
String response = fetchContent("http://url/", postdata);
where postdata is optional.
Thanks!
HttpClient sounds like what you want. You certainly can't do stuff like the above in one line, but it's a fully-fledged HTTP library that wraps up Get/Post requests (and the rest).
I would consider using the HttpClient library. From their documentation, you can generate a POST like this:
PostMethod post = new PostMethod("http://jakarata.apache.org/");
NameValuePair[] data = {
new NameValuePair("user", "joe"),
new NameValuePair("password", "bloggs")
};
post.setRequestBody(data);
// execute method and handle any error responses.
...
InputStream in = post.getResponseBodyAsStream();
// handle response.
There are a number of advanced options for configuring the client should you eventually required those.