by
7,365 32
1
7
7,489
15
Top 1% !
Popular
Famous
Pearl of Wisdom
Specified
Refined
OpenSource
Popularity: 791st place
Created
Modified Sep 18, 2013

Published on:

No tags for this snippet yet.
Architecturex86_64
InputName0url
InputName1data
InputType0String
InputType1String
JVMjre6
LanguageJava
LicenseMIT_X11
MethodNamesendPostReq
OSWindows
OutputTypeString

Send An HTTP POST Request In Java

This is a core method to send an HTTP POST Request in Java. It is able to store and re-use the set of cookies used in the past calls. It makes use of log4j library to log information regarding the process.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/11209/Send-An-HTTP-POST-Request-In-Java?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.client.CookieStore; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; private CookieStore m_cookies = null; //cookie container ready to receive the forms auth cookie public String sendPostReq(String url, String data) { // Create a new client: DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httppost.setHeader("Charset", "UTF-8"); httppost.setHeader("Accept", "application/json"); //access the secured service with the authorization cookie httpClient.setCookieStore(m_cookies); try { httppost.setEntity(new StringEntity(data, "UTF-8")); } catch (UnsupportedEncodingException e1) { log.error("Cannot encode data: " + data + " due to " + e1); return ""; } HttpResponse response = null; String res = ""; try { response = httpClient.execute(httppost); res = readStreamData(response.getEntity().getContent()); log.info("Response:" + res); } catch (org.apache.http.conn.HttpHostConnectException e) { log.error("Cannot receive response due to " + e); if (url.contains(LOGIN_URL)) res = TIMEOUT_RESP; } catch (IOException e) { log.error("Cannot parse incoming response due to " + e); } finally { httpClient.getConnectionManager().shutdown(); } //save cookies for the next secured run: m_cookies = httpClient.getCookieStore(); return res; }

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus