Created
May 31, 2012 20:38
-
-
Save JonasGroeger/2846066 to your computer and use it in GitHub Desktop.
HTTPPost request using the apache http client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We are going to post to this url. | |
HttpPost post = new HttpPost("http://example.com/login"); | |
// We are going to use the apache httpclient | |
HttpClient client = new DefaultHttpClient(); | |
// The request is going to have some parameters. | |
final HttpParams params = new BasicHttpParams(); | |
// Set the redirecting parameter in params to false. This will make sure we dont follow redirects like 302 and the result we get from the server later is the actual one and not some follow up resource. | |
HttpClientParams.setRedirecting(params, false); | |
// Use the paramers in the post | |
post.setParams(params); | |
try { | |
// We need some body for the POST request. | |
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3); | |
// Adding j_username=login | |
nameValuePairs.add(new BasicNameValuePair("j_username", "username")); | |
// Adding j_password=password | |
nameValuePairs.add(new BasicNameValuePair("j_password", "password")); | |
// Should be obvious | |
nameValuePairs.add(new BasicNameValuePair("other", "parameter")); | |
// We take the List of NameValuePairs and make a UTF-8 formatted URL encoded entity (ist a string basically) out of it. Then we give it to the post request | |
// The entity we provide is the BODY of the post request. It looks like this: | |
// "j_username=username&j_password=password&other=parameter" without the quotes. | |
post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")); | |
// We actually execute the request and receive a response | |
HttpResponse response = client.execute(post); | |
// Now is the time to work with the response. In this case we try to get a sessionID from the cookie the server sends us in return to the login. | |
Header[] headers = response.getHeaders("Set-Cookie"); | |
for (Header h : headers) { | |
Pattern sessionIDonly = Pattern.compile("(?<=JSESSIONID\\=)(.*?)(?=\\;)"); | |
Matcher matcher = sessionIDonly.matcher(h.getValue()); | |
matcher.find(); | |
String sessionID = matcher.group(); | |
return sessionID; | |
} | |
} catch (IOException e) { | |
// Basically, if anything goes wrong. You probaply want to use your own exception. | |
throw new Exception("Could not get SessionID"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment