How to send strings to server using Java? - java

I need to send a lot of strings to a web server using Java.
I have a List<String> with huge amount of strings and I need to send it via POST request to the Struts2 action on the server side.
I have tried something starting with
HttpPost httppost = new HttpPost(urlStr);
but don't know how to use it.
On other side I have a Struts2 action, and getting the POST request is easy to me.
I think this solution is too close, but it doesn't solve my problem because it's using just one string :
HTTP POST using JSON in Java
So, how to send many strings to a server using Java?

You should do somthing
HttpPost httppost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<>();
for(String s : list)
params.add(new BasicNameValuePair("param", s));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
on the other side is an action mapped to the url has setter for param. It should be
List<String> or String[]. The action when intercepted will populate that param property.

Related

POST/PUT via URL path vs via parameters in JAX-RS Jersey

I'm implementing a webservice in Java using the RESTful Jersey API.
I got a post request working using 2 distinct ways. You either post something to your server via a URL that includes the values of the fields you want to send in the URL path itself (e.g. http://server.se/Context_root/value1/value2/...) in the correct order defined at the server, and you simply:
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
Or you post always to the same URL (e.g. http://server.se/Context_root), and send the fields as parameters like so:
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params));
Where params is something like:
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
To which you simply add the name/value pair for each field you want to send:
params.add(new BasicNameValuePair(field, value));
Why are there 2 ways of doing the same thing in the same API? In what cases is one way preferable to the other?
Generally, the path parameters (http://server.se/Context_root/something) is to add in the context in the something object. For example, for a web service containing a set of cars (dealers with cars in inventory), you will add a car like this:
http://something.com/dealer1/cars. With the PathParam of your rest service, you will have access to the name of the dealer to add cars in it.
Instead, if you add a dealer, you don't need to specify anything (except maybe the city), then you will do http://something.com/dealers to post the new dealer information's.
The REST specification don't recommend to pass values of the objects with the path parameters.
As the wikipedia article says (http://en.wikipedia.org/wiki/Representational_state_transfer), the path is representing resources.

How to send POST request using HTTPURLConnection with JSON data

I have a RESTful API that I can call by doing the following:
curl -H "Content-Type: application/json" -d '{"url":"http://www.example.com"}' http://www.example.com/post
In Java, when I print out the received request data from the cURL, I correctly get the following data:
Log: Data grabbed for POST data: {"url":"http://www.example.com/url"}
But when I send a POST request via Java using HttpClient/HttpPost, I am getting poorly formatted data that does not allow me to grab the key-value from the JSON.
Log: Data grabbed for POST data: url=http%3A%2F%2Fwww.example.com%2Furl
In Java, I am doing this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post/");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
BasicNameValuePair nvp1 = new BasicNameValuePair("url", "http://www.example.com/url);
nameValuePairs.add(nvp1);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpresponse = httpclient.execute(httppost);
How do I make it so that the request from Java is similar to cURL in terms of how the data is sent?
The data you present as coming from the Java client are URL-encoded. You appear to specifically request that by using a UrlEncodedFormEntity. It is not essential for the body of a POST request to be URL-encoded, so if you don't want that then use a more appropriate HttpEntity implementation.
In fact, if you want to convert generic name/value pairs to a JSON-format request body, as it seems you do, then you probably need either to use a JSON-specific HttpEntity implementation or to use a plainer implementation that allows you to format the body directly.

POSTing arraylist

in most of the q&a its Name Value Pair that is used to POST;
List<NameValuePair> myBooks = new ArrayList<NameValuePair>();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(myBooks));
but when I try to change the params to to arrayList,
List<Books> myBooks= //fulfilled from another class"
I get this:
The constructor UrlEncodedFormEntity(List<myBooks>) is undefined
is it really impossible to post List instead of ValuePair without Jackson lib?
If you look at the API you can see that the list must must extend NameValuePair.
So your own class would need to extend the NameValuePair class as well.
But why would this be? If you look at the third line of the code you provided
httpPost.setEntity(new UrlEncodedFormEntity(myBooks));
The important part here is noticing the UrlEncodedFormEntity.
The UrlEncoded data would consist of simple name & value pairs, like this:
name=bob&age=20
If you provide a list that already consists of names with their values(NameValuePair), you get this done for you, by the library.
If you want to just POST arbitary data, you can do this by yourself, by using StringEntity.
httpPost.setEntity(new StringEntity(myString));
In any case, please do not forget to add the revelant content-type header to your POST!

Edit a value and post to http with HttpPost

The problem:I have a few forms in the html page which I want to edit, then submit the data.
I have read about entities in HttpClient, and I came across the UrlEncodedFormEntity, which as far as I understand you add parameters to it and then you can post them. I find this ok, but I thought is there a different way to post the changed attributes, since jsoup has a convenient method to set a value in an attribute. this is what I tried using a different entity, StringEntity:
HttpPost post = new HttpPost(url);
post.setHeader("User-Agent", USER_AGENT);
post.setHeader("Accept",
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
post.setHeader("Accept-Charset", "UTF-8");
post.setHeader("Cookie", getCookies());
post.setHeader("Connection", "keep-alive");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new StringEntity(updatedHTML, ContentType.TEXT_HTML));
HttpResponse response = null;
response = client.execute(post);
where updatedHTML is the full html code with the changes I want to post.
but as you guessed, its not working.
edit: I don't think it's the problem, but I also have a sumbit button, which I ignored here, should it also be considered in the updatedHTML?
Thanks for help.
Two things are wrong in your approach.
you cannot pass an html in the StringEntity as it is not the usage of the class
The StringEntity, as well as its derived classes, is intended to carry messages.
The second error is that you seem to use the library to change the html.
You need to work on what you are posting. Here an example.
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("your parameter name","your parameter value"));
formparams.add(new BasicNameValuePair("another parameter name","another paramete value"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost("http://localhost/");
httppost.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
I made some assumptions:
you have in your hands all the parameters you are passing (simply you will change the approach not working on the html but on the url)
The exception handling is not considered in my snippet. The code is a simple example to show you how to deal with forms
Note also that the UrlEncodedFormEntity will handle the parameters for you. E.g. in our example>
your parameter name=your parameter value&another parameter name=another parameter value

"Illegal Characters" in URL for HttpGet in Android get double-encoded

I am trying to find a solution to this the whole evening now...
I write an app which requests data from a web server. The Server answers in JSON format.
Everything works well except when I enter a umlaut like ä into my App.
In the following I assume the request URL is http://example.com/?q= and I am searching for "Jäger"
The correct call would then be h++p://example.com/?q=J%C3%A4ger
(Sorry for plus-signs but the spam protection doesnt let me post it correctly.)
So my problem is now:
When I give my URL String encoded or unencoded over to HttpGet it will always result in a doublee-encoded URL.
The Request to my Server is then http://example.com/?q=J%25C3%25A4ger (It encodes the percent signs)
which leads to the server searching in database for J%C3%A4ger what is obviously wrong.
So my question is how can I achive that if the user enters "Jäger" my app calls the correctly encoded URL?
Thanks for any help!
Here is the currently used code... Ist probably the worst possible idea I had...
URI url = new URI("http", "//example.com/?q=" + ((EditText)findViewById(R.id.input)).getText().toString(), null);
Log.v("MyLogTag", "API Request: " + url);
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse;
httpResponse = defaultClient.execute(httpGetRequest);
Update: Sorry, HttpParams isn't meant for request parameters but for configuring HttpClient.
On Android, you might want to use Uri.Builder, like suggested in this other SO answer:
Uri uri = new Uri.Builder()
.scheme("http")
.authority("example.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
HttpGet request = new HttpGet(uri.toString());
// This looks very tempting but does NOT set request parameters
// but just HttpClient configuration parameters:
// HttpParams params = new BasicHttpParams();
// params.setParameter("q", query);
// request.setParams(params);
HttpResponse response = defaultClient.execute(request);
String json = EntityUtils.toString(response.getEntity());
Outside of Android, your best bet is building the query string manually (with all the encoding hassles) or finding something similar to Android's Uri.Builder.

Categories