How to send simple http post request with post parameters in java - java

I need a simple code example of sending http post request with post parameters that I get from form inputs.
I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn't find a simple example of sending http post request with input parameters and getting text response.
Update: I'm interested in Apache HTTPClient v.4.x, as 3.x is deprecated.

Here's the sample code for Http POST, using Apache HTTPClient API.
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostExample {
public static void main(String[] args){
String url = "http://www.google.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("p", "apple");
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsStream();
}
System.out.println(in);
} catch (Exception e) {
e.printStackTrace();
}
}
}

I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.
Arshak
https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java
private void postEvents()
{
DefaultHttpClient client = new DefaultHttpClient();
/** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */
HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents");
JSONObject holder = new JSONObject();
JSONObject eventObj = new JSONObject();
Double budgetVal = 99.9;
budgetVal = Double.parseDouble(eventBudgetView.getText().toString());
try {
eventObj.put("budget", budgetVal);
eventObj.put("name", eventNameView.getText().toString());
holder.put("myevent", eventObj);
Log.e("Event JSON", "Event JSON = "+ holder.toString());
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
post.setHeader("Content-Type","application/json");
} catch (UnsupportedEncodingException e) {
Log.e("Error",""+e);
e.printStackTrace();
} catch (JSONException js) {
js.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol",""+e);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO",""+e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
Log.e("IO E",""+e);
e.printStackTrace();
}
}
Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show();
}

HTTP POST request example using Apache HttpClient v.4.x
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);

http://httpunit.sourceforge.net/doc/cookbook.html
use PostMethodWebRequest and setParameter method

shows a very simple exapmle where you do post from Html page, servlet processes it and sends a text response..
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html

Related

Move CloseableHttpResponse inside nested try with resources

I have the following code using try with resources with CloseableHttpResponse
CloseableHttpResponse response = null;
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
//code...
response = httpClient.execute(target, post);
String responseText = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.error("Failed sending request", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
logger.error("Failed releasing response", e);
}
}
}
Can I safely replace with nested try with resources:
try (CloseableHttpClient httpClient = HttpClients.custom().build()){
URIBuilder uriBuilder = new URIBuilder(url);
HttpHost target = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme());
HttpPost post = new HttpPost(uriBuilder.build());
try (CloseableHttpResponse response = httpClient.execute(target, post)) {
String responseText = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
logger.error("Failed sending request", e);
}
Or is it better to use a single try with resources block:
try (CloseableHttpClient httpClient = HttpClients.custom().build();
CloseableHttpResponse response = getResponse(httpClient, url)) {
Sometime refactoring to single block is problematic, so I wanted to know the a nested/additional block is a valid solution.
HttpClient never returns a null HttpResponse object. The first construct is simply not useful. Both the second and the third constructs are perfectly valid

How can I set default headers for all requests?

I have a lot of requests. How can I set default headers for all requests? Please, give me examples
Now My code look like this:
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.addHeader("content-type", "application/json");
request.setEntity(params);
try {
client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
So I have many requests like this
Since you're using the HttpClientBuilder, why not try using its setDefaultHeaders() method?
HttpClientBuilder client = HttpClientBuilder.create();
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
client.setDefaultHeaders(header);
HttpPost request = new HttpPost(url);
StringEntity params = null;
try {
params = new StringEntity(o.writeValueAsString(auth));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
request.setEntity(params);
try {
client.build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
e.printStackTrace();
}
Hope that helps!
The most awkward are the try-catches. Best would be to throw them to the caller, and rely on the logging there.
However a single try-catch is possible too. There the style declaration of var + try{ assigning to var } processing var should better be try { declaration + assigning + processing }
Then one already gets shorter, more readable code.
HttpPost request = new HttpPost(url);
request.addHeader("content-type", "application/json");
try {
request.setEntity(new StringEntity(o.writeValueAsString(auth)));
HttpClient client = HttpClientBuilder.create().build();
HttpResponse response = client.execute(request);
} catch (IOException e) {
Logger.log(Level.SEVERE, e);
}
The HttpClient part is still a bit dubious, and could be reduced without declaration.
Alternatives exist like using annotations, Spring and some more declarative techniques. But this is short enough.

Odata V4 Client: getEntityCreate method

I developed an ODataClient in Java in order to create new entities. I am encountering difficulties to create new entities. I took the initiative to see all messages sent by my client with Fiddler.
ODataEntityCreateRequest<ClientEntity> request=
client.getCUDRequestFactory()
.getEntityCreateRequest(new URI("http://localhost:8888/"), clientEntity);
request.addCustomHeader("Content-Type", "application/json;odata.metadata=minimal");
request.setAccept("application/json;odata=minimalmetadata");
ODataEntityCreateResponse<ClientEntity> response = request.execute();
below the first line of the body I obtained with Fiddler:
17b
{"#odata.type":"#ODataDemo.Product", ....}
I tested manually with Fiddler to create a new entity and the first line of message body should be:
{"odata.type":"ODataDemo.Product", ....}
I would like to know if it possible to set the body of the request with Odata in order to delete "#" and "#".
Thanks,
I found an alternative solution to this problem. I do not use entirely OData libraries. I created methods to to the post Request.
public void insertData(String entityName, Entity entity)
{
try {
ResWrap<Entity> resW = new ResWrap<Entity>(new URI(this.baseURI.concat("/").concat(entityName)), "full", entity);
ClientEntity clientEntity = this.client.getBinder().getODataEntity(resW);
//String message = getMessageRebuild(client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON));
InputStream is = client.getWriter().writeEntity(clientEntity, ContentType.APPLICATION_JSON);
if(is != null)
{
System.out.println("POST: "+post(this.baseURI.concat("/").concat(entityName), is));
//System.out.println("POST:"+post("http://localhost:8888/"+entityName, is));
}
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ODataSerializerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String post(String url,InputStream message) throws Exception{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
//post.addHeader("Content-Type", "application/json;odata.metadata=minimal");
//post.addHeader("Accept", "application/json;odata=verbose");
post.addHeader("Content-Type", "application/json");
post.addHeader("Accept", "application/json");
HttpEntity entity = new ByteArrayEntity(IOUtils.toByteArray(message));
post.setEntity(entity);
HttpResponse response = client.execute(post);
String result = EntityUtils.toString(response.getEntity());
return result;
}
insertData take two parameters : entityName + Entity I generated.
I use the librairie org.apache.http to send the http message to the OData Server.

HTTPResponse's string from Play is empty

I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.

Java HTTP Request Stuck

I've never really used http requests in Java, I'm trying to make a request that would basically recreate this http://supersecretserver.net:8080/http://whateverwebsite.com
This server takes whatever website and returns only the text of the page in the body of the response.
The code is as follows:
public String getText(String webPage) throws ParseException, IOException{
HttpResponse response = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://supersecretserver.net:8080/" + "http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/"));
response = client.execute(request);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String responseBody = "No text found on webpage.";
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
responseBody = EntityUtils.toString(entity);
}
}
System.out.println("Returning Response..");
System.out.println(responseBody);
return responseBody;
}
It seems to get stuck on
response = client.execute(request);
I'm not sure what the problems is, any insight would be helpful.
Seems likely that your HttpClient is not timing out, you can set a timeout value by following this example (from http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/)
You just to have to consider a timeout value that makes sense for you.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
Also as your HttpClient is not connecting (since it's getting stuck) you should also take into consideration why is that happening (maybe you need to configure a proxy?)

Categories

Resources