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);
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 pretty new concerning REST api and POST request.
I have the url of a REST api. I need to access to this api by doing an API call in JAVA thanks to a client id and a client secret (I found a way to hash the client secret). However, as I am new I don't know how to do that api call. I did my research during this all day on internet but I found no tutorial, website or anything else about how to do an api call. So please, does anyone know a tutorial or how to do that? (if you also have something about POST request it would be great)
I would be very thankful.
Thank you very much for your kind attention.
Sassir
Here's a basic example snippet using JDK classes only. This might help you understand HTTP-based RESTful services a little better than using a client helper. The order in which you call these methods is crucial. If you have issues, add a comments with your issue and I will help you through it.
URL target = new URL("http://www.google.com");
HttpURLConnectionconn = (HttpURLConnection) target.openConnection();
conn.setRequestMethod("GET");
// used for POST and PUT, usually
// conn.setDoOutput(true);
// OutputStream toWriteTo = conn.getOutputStream();
conn.connect();
int responseCode = conn.getResponseCode();
try
{
InputStream response = conn.getInputStream();
}
catch (IOException e)
{
InputStream error = conn.getErrorStream();
}
You can also use RestTemplate from Spring: https://spring.io/blog/2009/03/27/rest-in-spring-3-resttemplate
Fast and simple solution without any boilerplate code.
Simple example:
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
map.add("firstParamater", "parameterValue");
map.add("secondParameter", "differentValue");
rest.postForObject("http://your-rest-api-url", map, String.class);
The Restlet framework also allows you to do such thing thanks to its class ClientResource. In the code below, you build and send a JSON content within the POST request:
ClientResource cr = new ClientResource("http://...");
SONObject jo = new JSONObject();
jo.add("entryOne", "...");
jo.add("entryTow", "...");
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Restlet allows to send any kind of content (JSON, XML, YAML, ...) and can also manage the bean / representation conversion for you using its converter feature (creation of the representation based on a bean - this answer gives you more details: XML & JSON web api : automatic mapping from POJOs?).
You can also note that HTTP provides an header Authorization that allows to provide authentication hints for a request. Several technologies are supported here: basic, oauth, ... This link could help you at this level: https://templth.wordpress.com/2015/01/05/implementing-authentication-with-tokens-for-restful-applications/.
Using authentication (basic authentication for example) can be done like this:
String username = (...)
String password = (...)
cr.setChallengeResponse(ChallengeScheme.HTTP_BASIC, username, password);
(...)
cr.post(new JsonRepresentation(jo), MediaType.APPLICATION_JSON);
Hope it helps you,
Thierry
I have a strange problem I have been trying to solve for the last two days, and seem to have narrowed it down to the cookies attached to the global DefaultHttpClient variable associated with my application.
When I use the client with post params, everything hangs after the first time it is used. I don't get any requests to my server, the application just refuses to do anything. If there are no post parameters, everything works just fine. Here is the applicable code.
httppost.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));
DefaultHttpClient defhttpClient = new DefaultHttpClient();
logger.info("URL Encoded");
//When I pass the cookies things stop working...
//defhttpClient.setCookieStore(httpclient.get_cookies());
response = defhttpClient.execute(httppost);
logger.info("Received response");
If I make a new DefaultHttpClient and run the post request with parameters, the client can talk to the server just fine. The only problem is that I need the cookies from the old client to tell the server who the current user is. When I take the cookies from my old client and give them to my new one, the application hangs. Again, I dont even see a request coming into my server.
Does anyone have any idea what's going on here?
Alright, so I couldn't figure out how to do this by sending the message in the body with setentity. Just decided to put the json data in the header instead and everything seems to work fine. Not really too big of a problem. Would have preferred to do it the right way, but sometimes you can't get everything you want. Here is the code for anyone with the same problem.
JSONObject post_params = new JSONObject();
for(NameValuePair pair : pairs){
post_params.put(pair.getName(), pair.getValue());
}
httppost.setHeader("json",post_params.toString());
response = httpclient.get_client().execute(httppost);
I'm working on a Java application using Seam and I need to forward to a page on a different site, sending some POST data along with it. It needs to occur from the backend.
Any ideas how I can accomplish this?
EDIT: I don't merely need to receive the response - I need to actually direct the user to the new page.
Take a look at HttpClient, you should be able to generate your POST request programatically from the backend, e.g:
PostMethod post = new PostMethod("http://myserver/page.jsp");
post.addParameter("parameter1", "value1");
post.addParameter("parameter2", "value2");
More details here:
http://weblogs.java.net/blog/2006/11/01/quick-intro-httpclient
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.