I'm trying to fill form from Java program for Android and send request to the server. First I tried to use a Selenium for Android, but I failed to start it, then I found to many examples about, how to use HttpPost etc.., but the action of the form is:
form name="mainform" method="POST" action="/system/boxuser_edit.lua"
So I found the following code, and I tried to many possible combination, but without success
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),100000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 100000);
String SID = "xxxxxxxxx";
HttpPost httpPost = new HttpPost("http://fritz.box/system/boxuser_edit.lua?sid="+SID+"=new");
BasicNameValuePair emailBasicNameValuePair = new BasicNameValuePair("user", paramUsername);
BasicNameValuePair passwordBasicNameValuePair = new BasicNameValuePair("password", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePair);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
i have just bunch of questions before we discuss your code because what you did here seems to be correct.
First of all did you request a permission to access network in the manifest file?
if it's not this is how you do it:
add this line of code to your androidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
But before that you have to check that the link you are passing to the HttpPost Object is working, you can use a web browser to test it, because i just did that right now and it seems that it doesn't work!!
Related
public String POST(String url){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("UserName","example#gmail.com");
jsonObject.accumulate("Password","123456!");
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
Toast.makeText(getBaseContext()," text",Toast.LENGTH_SHORT).show();
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
// Toast.makeText(getBaseContext(), "post invoked", Toast.LENGTH_SHORT).show();
return POST(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Data Sent!"+result+" don", Toast.LENGTH_LONG).show();
}
}
I tried to invoke this POST method from an object of HTTPAsyncTask class, with targeted url passed. But the Toast execeuted in OnPostExecute() popping up with the message "Data sent!Done", which tells that value of 'result' variable is null. And in log cat it is showing"I'm getting feedback from logcat that "Request time failed,Java.net.socketException:Addres family not supported by protocol". What would the fault? Could anyone please fix this***
The URL is lacking the protocol part. Try
http://devcare.dyndns.info:85/WCFServices/UserAuthServices.svc/Login
otherwise devcare.dyndns.info will be mistaken as the protocol.
Try adding this to AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
And please catch this exception:
catch(SocketException se)
{
Log.e("Exception ---- : " , "Error on execute??" + se.getMessage());
se.printStackTrace();
}
I've created basic android apps in various programming classes that I have taken before using Eclipse and the Java Android SDK.
The app that I'd like to create would require users to enter information that would later be analyzed. I want people to be able to compare this data with other people's data so I'd like every entry that users make to be submitted to a database to later be queried when a person attempts to compare their data.
I'd like direction for how to accomplish this. Should I find a free hosting site and set up a Sql server or is there a better way to accomplish this?
Edit: Just for fun.
I am a very beginner android developer, and I have found that using cloud-stored online database like mongolab.com is very friendly for user submitted data. The communication between database and server will have to be done through JSON parsing and URI requests.
Here is example of code you can bind to a button that will send object stored in field tempData:
public void send(View view) {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA?apiKey="
+ apiKey;
try {
// make web service connection
final HttpPost request = new HttpPost(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string with GSON library
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(tempData);
String json = gson.toJson(jsonElement);
StringEntity entity = new StringEntity(json);
Log.d("****Parameter Input****", "Testing:" + json);
request.setEntity(entity);
// Send request to WCF service
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, Void>() {
#Override
public Void doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving: "
+ response.getStatusLine().toString());
// Get the status of web service
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is an example of code used to retrieve elements in the database:
public void load() {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA"
+ "?apiKey=" + apiKey;
Log.d("****Status Line***", "" + apiURI);
try {
// make web service connection
final StringBuilder builder = new StringBuilder();
final HttpGet request = new HttpGet(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, String>() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
doSomethingWithReceivedData(result); //THIS METHOD IS DEFINED IN BODY OF YOUR ACTIVITY
}
#Override
public String doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.d("****Status Line***", "Success");
return builder.toString();
} else {
Log.d("****Status Line***",
"Failed to download file");
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
You should have a data base to store the data. Like mentioned above, the data base is good to be in MySQL (SQL). Your application should have a method that can POST the results to the server, where the server will read the string send and retrieve and store the data.
A good start is to read about JSON
and read also about Asynctask
Also you need to know how to build your sever part. A good idea is to start with PHP, but I am not an expert on that field.
I hope this helps you start your project.
Simple, no DB required.
Usergrid by Apigee is exactly what you are looking for!
You can store each user's details
Retrieve stored data
Send events and receive event callbacks across devices
Best of all - no server side code. Only APIs
FYI This is the direction you should be heading even if you know how to code a server.
PS: I don't work for apigee or usergrid.
I need to send http POST request from mobile android application to the server side applcation.
This request need to contain json message in body and some key-value parametres.
I am try to write this method:
public static String makePostRequest(String url, String body, BasicHttpParams params) throws ClientProtocolException, IOException {
Logger.i(HttpClientAndroid.class, "Make post request");
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(body);
httpPost.setParams(params);
httpPost.setEntity(entity);
HttpResponse response = getHttpClient().execute(httpPost);
return handleResponse(response);
}
Here i set parametres to request throught method setParams and set json body throught setEntity.
But it isn't work.
Can anybody help to me?
You can use a NameValuePair to do this..........
Below is the code from my project where I used NameValuePair to sent the xml data and receive the xml response, this will provide u some idea about how to use it with JSON.
public String postData(String url, String xmlQuery) {
final String urlStr = url;
final String xmlStr = xmlQuery;
final StringBuilder sb = new StringBuilder();
Thread t1 = new Thread(new Runnable() {
public void run() {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlStr);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
1);
nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.d("Vivek", response.toString());
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sb.append(s);
}
Log.d("Check Now",sb+"");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t1.start();
try {
t1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sb.toString());
return sb.toString();
}
Hi i am using below code to send data to server
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.myurl.com/app/page.php");
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("name", "dave"));
nameValuePairs.add(new BasicNameValuePair("taxi no", "354"));
nameValuePairs.add(new BasicNameValuePair("pack", "0"));
nameValuePairs.add(new BasicNameValuePair("exchk", "1"));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I can successfully send data to server,but the server return larger amount of data(100Kb-200KB) in text format.I want to convert that text response into json object.so i am assigning all the response into one string to convert json object.
But That Response string contain only less amount of data.
I checked the server it send 112kb file but that response String contain only less data.say around (50kb-75kb).
So can u please any one guide me to solve the problem
ArrayList is an expandable List item. So I have no idea what the purpose of using "5" as an argument. Second thing is BasicNameValuePair contains names and values as arguments. It is a good practice to use single word for a name attribute. Remove
String responseBody = EntityUtils.toString(response.getEntity());
Add following code sample
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
This return the page content in a readable format. Then you can pass it to a JSON file by using JSONObject and JSONArray.
I have get a correct login using HttpRequest to work. It prints the correct html form of the logn page in my toast (just for testing). Now I want to set a cookie from that request. How is this possible?
If it necessary I can provide some code.
I already know about the CookieManager class, but how can I successfully do it?
Thanks in advance!
My code:
public String getPostRequest(String url, String user, String pass) {
HttpClient postClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("login", user));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
response = postClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
instream.close();
return result;
}
}
} catch (Exception e) {}
Toast.makeText(getApplicationContext(),
"Connection failed",
Toast.LENGTH_SHORT).show();
return null;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Well, this is pretty much it. convertStreamToString() function converts the InputStream into a String (plain HTML code), which I "toast" out to just test it (so it work), so the code is working though. Now to set the cookie. :-)
This is what I've reached for now:
// inside my if (entity != null) statement
List<Cookie> cookies = postClient.getCookieStore().getCookies();
String result = cookies.get(1).toString();
return result;
When I have logged in, the CookieList id 1 contains a value, otherwise the value is standard. So for now I know the difference in value, but how can I continue?
I think Android ships with Apache HttpClient 4.0.
You can check Chapter 3. HTTP state management topic from HttpClient Tutorial.
You can also refer similar questions on SO:
Android project using httpclient --> http.client (apache), post/get method
How do I manage cookies with HttpClient in Android and/or Java?
Also Check this example for usage: http://svn.apache.org/repos/asf/httpcomponents/httpclient/branches/4.0.x/httpclient/src/examples/org/apache/http/examples/client/ClientFormLogin.java