Monday 17 March 2014

RESTful Java Client With Apache HttpClient using POST


If you are using maven you can get httpclient from:

<dependency>
<groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.1.1</version>
 </dependency>

So this is my implementation of an RESTful java web service using POST.
I decided I should make this because I see a lot of tutorials on how to make a GET restfull service but I didn't find one with POST, or what I have found did not really work for me.



Code:

@Path("/login")
public class LogIn {

@SuppressWarnings("unchecked")
@POST
@Path("/userlogin")
@Produces(MediaType.TEXT_HTML)
//@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response printMessage(@FormParam("username") String username,
@FormParam("password") String password) {


return Response.status(200).entity("what to return")).build();
}
}

And the client

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class MainTest {

public static void main(String[] args) throws IOException,
URISyntaxException {
BasicCookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore).build();

HttpUriRequest login = RequestBuilder
.post()
.setUri(new URI(
"http://localhost:8080/projectname/login/userlogin/"))
.addParameter("username", "yourusername")
.addParameter("password", "yourpassword").build();
CloseableHttpResponse response = httpclient.execute(login);

if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));

String outputF = new String("");
String output = new String("");
while ((output = br.readLine()) != null) {
outputF = outputF + output;
}
System.out.println("Recived: " + outputF);

}

}

No comments:

Post a Comment