In java while doing an HTTP post request using nameValuePairs we write the following code!
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sometesturl.com");
JSONObject json = new JSONObject();
json.put("id",1);
json.put("name","john");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("data", "abc"));
nameValuePairs.add(new BasicNameValuePair("samplejson", json.toString()));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
As seen over here we use the UrlEncodedFormEntity to encode our request body. Similarly, I need to do the same in Javascript. I have seen the EncodeURIComponent method but that doesn't seem to encode the request body. Instead it encodes the URL.
Can someone tell me how to encode the request body in javascript?
Related
I want to read two numbers (randomly generated) from a website which are then used in order to compute a result and then submit the result using a POST request. To do so, I will also need to submit the cookie of that session so that the system is aware of the random numbers which have been produced in that particular session.
In order to read the numbers I am using Jsoup:
Document document = Jsoup.parse(Jsoup.connect("http://website.com/getNumbers").get().select("strong").text());
String[] numbers = document.text().split(" ");
String answer = methodThatComputesTheDesiredOutput(numbers);
Now I want to send a POST request that includes answer and cookies of that session. Here's a partially implemented POST request that includes only the one parameter (answer):
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("answer", answer);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
How can I obtain the cookie when reading the document and then use it as a parameter of the POST request?
Extract cookies using jsoup in the following way:
Response response = Jsoup.connect("http://website.com/getNumbers").execute();
Map<String, String> cookies = response.cookies();
Document document = Jsoup.parse(response.body());
Create a BasicCookieStore using the cookies extracted using jsoup. Create a HttpContext containing the cookie store and pass it while executing your next request.
BasicCookieStore cookieStore = new BasicCookieStore();
for (Entry<String, String> cookieEntry : cookies.entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
cookie.setDomain(".example.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);
}
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
List<NameValuePair> params = new ArrayList<NameValuePair>(1);
params.add(new BasicNameValuePair("answer", answer);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
httpClient.execute(httpPost, localContext);
Send your first request like below :-
Response res = Jsoup.connect("login Site URL")
.method(Method.GET)
.execute();
Now get the cookies and send new request with the cookies something like below :-
CookieStore cookieStore = new BasicCookieStore();
for (String key : cookies.keySet()) {
Cookie cookie = new Cookie(key, cookies.get(key));
cookieStore.addCookie((org.apache.http.cookie.Cookie) cookie);
}
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://website.com/submitAnswer");
httpClient.execute(httpPost,context);
I have an app that sends an object to an api via HttpPost. I have some sample such:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("Destination", destination));
nameValuePairs.add(new BasicNameValuePair("Description", description));
nameValuePairs.add(new BasicNameValuePair("CreatorName ", myName));
In this object, I have an array of "User" objects, which has a DisplayName and Phone. How can I send this array through HttpPost? The following is not recognized by the server (where the quotes are escaped):
nameValuePairs.add(new BasicNameValuePair("Users", "[{"Destination":"St.Louis", "Phone":"1234"}]"));
Simplest way is to convert the Array as String (or JSON string). Then encode it with your server after passing as entity.
try this
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppostreq = new HttpPost(wurl);
StringEntity se = new StringEntity(nameValuePairs.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
httppostreq.setEntity(se);
HttpResponse httpresponse = httpclient.execute(httppostreq);
I think this code should work.
nameValuePairs.add(new BasicNameValuePair("user[0]", gson.toJson(users.get(0))));
nameValuePairs.add(new BasicNameValuePair("user[1]", gson.toJson(users.get(1))));
I would like to send a json string using httpost(apache). I have two ways to do it.
I can make it as a parameter like this :
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("json",myJsonString));
httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
or I can make it as request body:
StringEntity params =new StringEntity(myJsonString);
request.addHeader("content-type", "application/json");
request.setEntity(params);
Which way I should do if myJsonString is very large? I'm using the 1st way because in servlet I just need to read it as a parameter.
How represente the curl command using the HttpPost:
curl --form "tag=mytag" --form "archive=#c:/etc/test.pdf;type=application/pdf" ...
Below is my code:
HttpPost httpPost = new HttpPost(www.resourceURL.com);
httpPost.setHeader(Authorization: bearer cb084803-ba48-xxxx-xxxx-2a275e199c38)
....
below is the code I've done:
But i receive the HTTP 500 error
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
HttpPost httpPost = new HttpPost(resourceURL);
httpPost.setHeader(OAuthConstants.AUTHORIZATION, bearer cb084803-ba48-xxx-xxx-2a275xxx99c38 ));
httpPost.setHeader(OAuthConstants.CONTENTE_TYPE, OAuthConstants.ENCODED_CONTENT_DATA);
httpPost.setHeader(OAuthConstants.PARTNERUSERID, login);
//------------------------------------------------------------------------
parameters.add(new BasicNameValuePair("title", doc.getTitre()));
parameters.add(new BasicNameValuePair("tag", doc.getTag()));
parameters.add(new BasicNameValuePair("archive", "#" + doc.getPath() + ";type=application/pdf"));
httpPost.setEntity(new UrlEncodedFormEntity(parameters));
//------------------------------------------------------------------------
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = null;
response = httpClient.execute(httpPost);
code = response.getStatusLine().getStatusCode();
I do not know how to solve this problem
I check content the contenet of response and i have this result:
[{"error":"bad_request","error_description":"malformed Json : Expected BEGIN_OBJECT but was STRING at line 1 column 1"}]
Create a UrlEncodedFormEntity and add your form elements there
List<NameValuePair> formEntries = new ArrayList<>(); // or whatever List sub-type
formEntries.add(new BasicNameValuePair("tag", "my-tag"));
// more
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formEntries);
httpPost.setEntity(entity);
I tryied to find some information about this but is a bit difficult since all i found is about javascript instead of java,
I want to know how i can get it in php too because i m not sure how to do it
I am trying to pass an array multidimensional by post, i have no idea how to pass a multdimensional array by java this is my code(i suppose that i only will need to change a few)
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://web");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
for (int count=0; count < array.length; count++)
{//this loop is what i need to change but i dont know how to do it
nameValuePairs.add(new BasicNameValuePair("foto",array[count][0]));
nameValuePairs.add(new BasicNameValuePair("media",array[count][1]));
nameValuePairs.add(new BasicNameValuePair("votos",array[count][2]));
}
if(nameValuePairs != null) httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.execute(httppost, responseHandler);
}
I think you should serialize the data to JSON/XML/CSV format and parse it on the server side. Otherwise it will be not so intelligent code.