Im a newbie at android coding and I looked around a little to try to find a solution to my problem. The web-site I want to send the data has a form. I want to collect data from my activity in edittext fields and send it to the Web form and submit the web-form.
After some reading online I am across the below method. Can someone tell me if this is correct? If the webform has a field called "name" (I can access the site source). And the user enters "John Doe", So the NameValue pair will be "name","John Doe" right?
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),10000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(),10000);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name1", "value1"));
nameValuePairs.add(new BasicNameValuePair("name2", "value2"));
nameValuePairs.add(new BasicNameValuePair("name3", "value3"));
// etc...
try{
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
}
catch(Exception e)
{
}
Yes, you are submitting the data via post.
Just in case you don't know this: You should post the data to the "form action" page.
Yes, what ever data you want to send you need to add to nameValuePairs
nameValuePairs.add(new BasicNameValuePair("name", "Jhon Deo"));
Related
I want to get the JSON data from solarwinds orion rest api and have to write those JSON data in excel file.
I'm assuming you need a java program to send a post request to an API endpoint. ApacheHTTP library to the rescue. You can read more from the documentation here. Even more information in the official apache website
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://www.a-domain.com/foo/");
// Request parameters and other properties.
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("param-1", "12345"));
params.add(new BasicNameValuePair("param-2", "Hello!"));
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream instream = entity.getContent()) {
// do something useful
}
}
Taken from this answer
I've been using lots of HTTP posts in my apps recently and I've always been using this template:
HttpPost httpPost = new HttpPost(server);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","John"));
nameValuePairs.add(new BasicNameValuePair("age",13+""));
...
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpClient.execute(httpPost);
And on the server's PHP script:
$name = $_POST['name'];
$age = $_POST['age'];
...
This has always worked perfectly. However, recently I got a request that the data should actually be a JSON itself which would contain all those key-value pairs.
To be more explicit, the PHP script has been written to do this:
$json = $_POST['data'];
$name = $json['name'];
$age = $json['age'];
...
While this is an awkwardly simple modification, I can't seem to make it work in the Android code, i.e. I can't find the correct way to add the JSON to the HTTP data.
I'm doing this:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
...
But what to do next?? How can I add this JSON to the HTTP with the key "data"?
I've tried this:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("data", json.toString()));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
But I'm not sure it's the right way to do it and also the server's response is signalling an error.
How should I do it? How should I GENERALLY add a JSONObject with a key, or even a JSONArray?
Thanks!
EDIT: Please don't send me to other SO links, I've looked and none is answering straight to my point.
Generally write json:
http://www.vogella.com/tutorials/AndroidJSON/article.html#androidjson_write
For your task, you don't need to put your json into a list. Just do
httpPost.setEntity(new UrlEncodedFormEntity(json.toString()));
//or else use this
httpPost.setEntity(new StringEntity(json.toString(), HTTP.UTF_8));
EDIT:
JSONObject json = new JSONObject();
json.put("name", "John");
json.put("age", 13+"");
JSONObject data = new JSONObject();
data.put("data", json.toString());
httpPost.setEntity(new UrlEncodedFormEntity(data.toString()));
I am trying make a JSON call to a server using HttpClient API. The code sinppet is shown below.
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpPost(URLString);
HttpResponse response = httpClient.execute(httpPost);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("method", "completeUserLogin"));
String[] params = new String[]{"100408"};
response = httpClient.execute(httpPost);
I want to add params to nameValuePairs. BasicNameValuePair class does not allow you to add arrays. Any thoughts?
Thanks in advance!
Look at this . Here they pass the array in BasicNameValuePairs.Here the colours is the array which we are going to send on a server. You should use your array varible instead of colours.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("colours[0]","red"));
nameValuePairs.add(new BasicNameValuePair("colours[1]","white"));
nameValuePairs.add(new BasicNameValuePair("colours[2]","black"));
nameValuePairs.add(new BasicNameValuePair("colours[3]","brown"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
If you are posting data in json format then you should not post params like this. Instead create a JSONObject put these values in that json object, and get a string from that json object and then create a StringEntity, and set this Entity to HttpPost object.
Creating JSONObject for the Request:
JSONObject json=new JSONObject();
json.put("method", "completeUserLogin");
JSONArray arr= new JSONArray();
arr.put("100408");
json.put("params", arr);
String params=json.toString();
I've generate an HTMLPost Request containing a JSON object in java and would like to parse it in PHP.
public static String transferJSON(JSONObject j) {
HttpClient httpclient= new DefaultHttpClient();
HttpResponse response;
HttpPost httppost= new HttpPost(SERVERURL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);
}
And on the server
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// input = "json=%7B%22locations%22%3A%5B%7B%22..."
$input = file_get_contents('php://input');
// jsonObj is empty, not working
$jsonObj = json_decode($input, true);
I guess this is because the JSON special characters are encoded.
The json_decode return empty response
Any idea why ?
Instead of POSTing an application/json entity, you are actually posting an HTTP form entity (application/x-www-form-urlencoded) with a single value pair json=(encoded json).
instead of
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("json", j.toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Try
httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8"));
That's by design: you are accessing the raw POST data, which needs to be URLencoded.
Use urldecode() on the data first.
Try this:
//remove json=
$input = substr($input, 5);
//decode the url encoding
$input = urldecode($input);
$jsonObj = json_decode($input, true);
Here is Java code that POSTs data to a website and than gets redirected as a response (status 302). It works perfectly on my PC (Eclipse, Java, Ubuntu), it does exactly what I want it to do.
I tried quite everything to post the code functionality but I just am not able to.
Java code:
// Preparing the CLIENT and POST Method
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://na.leagueoflegends.com/ladders/solo-5x5");
try {
// Add your POST METHOD attributes
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("op", "Search"));
nameValuePairs.add(new BasicNameValuePair("player", "Jaiybe"));
nameValuePairs.add(new BasicNameValuePair("ladder_id", "3"));
nameValuePairs.add(new BasicNameValuePair("form_build_id",
"form-526370b788622996caa3669e7b975ccf"));
nameValuePairs.add(new BasicNameValuePair("form_id",
"ladders_filter_form"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
// RESPONE THAT WORKS WITH JAVA
System.out.println("Location:");
String LocationHeader = response.getFirstHeader("location").getValue();
System.out.println(LocationHeader);
System.out.println();
// To get the BODY I would have to parse that again - since its not REDIRECTING automatically
HttpClient httpclient2 = new DefaultHttpClient();
HttpPost httppost2 = new HttpPost(LocationHeader);
response = httpclient2.execute(httppost2);
System.out.println("And EVEN the response body:");
System.out.println(EntityUtils.toString(response.getEntity()));
Code does:
Posts
Gets Redirected - gets header of Location
Parses the Location
And I need android to do the same. Either "Location" or body of repsonse, is ok, I dont need both.
The post: http://www.anddev.org/networking-database-problems-f29/httppost-clientprotocolexception-t56118.html
I have found the problem!
httpclient.getParams().setParameter("http.protocol.version",
HttpVersion.HTTP_1_0);
Just changing this one line - version 1_0 works and 1_1 does not. Don't ask me why :)
Thank you all!
Please try the following code. The location in the header is missing, because the page has already redirected. So we can disable redirection to get the location tag.
httpclient.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
Try calling this after you create your http client so that it follows your redirect
httpclient.getParams().setParameter("http.protocol.allow-circular-redirects", true);