I have an application built that works like a form, it takes four fields and validates the information in order to make sure that no invalid characters are entered. These four fields are stored in variables:
- Phone
- Name
- Email
Comments
Now I want to submit the form data (whatever is entered into these four fields and stored to the variables) to a url (will use http://www.test.com), but I am not sure how to go about doing this. I think I am looking for something called the HttpURLConnection, but I am not sure how to specify which variable is sent. The code below I found from the website http://developer.android.com/reference/java/net/HttpURLConnection.html
private class UploadFilesTask extends AsyncTask<URL, Integer, Long>{
protected Long doInBackground(URL... urls) {
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.test.com");
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("phone", "value"));
data.add(new BasicNameValuePair("name", "value"));
data.add(new BasicNameValuePair("email", "value"));
data.add(new BasicNameValuePair("comments", "value"));
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = http.execute(post);
// do something with the response
}
catch (ClientProtocolException e) {
// do something
finish();
}
catch (IOException e) {
// do something
finish();
}
}
}
Any help would be much appreciated, thank you!
The simplest way to send form data to a server is to use HttpClient, and HttpPost.
Try something like this:
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.example.com/process");
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("phone", "value");
data.add(new BasicNameValuePair("name", "value");
data.add(new BasicNameValuePair("email", "value");
data.add(new BasicNameValuePair("comments", "value");
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = http.execute(post);
// do something with the response
}
catch (ClientProtocolException e) {
// do something
}
catch (IOException e) {
// do something
}
Note, you'll want to perform this operation in an AsyncTask so you don't lock up the UI thread waiting for the networking operations to complete.
Edit
Here's a simple quick example of what it might look like in an AsyncTask.
public class SendTask extends AsyncTask<Void, Void, Boolean> {
String responseString;
@Override
protected Boolean doInBackground(Void... params) {
try {
HttpClient http = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.test.com");
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("phone", "value"));
data.add(new BasicNameValuePair("name", "value"));
data.add(new BasicNameValuePair("email", "value"));
data.add(new BasicNameValuePair("comments", "value"));
post.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = http.execute(post);
responseString = new BasicResponseHandler().
handleResponse(response); // Basic handler
return true;
}
catch (ClientProtocolException e) {
// do something useful to recover from the exception
// Note: there may not be anything useful to do here
}
catch (IOException e) {
// do something useful to recover from the exception
// Note: there may not be anything useful to do here
}
return false;
}
@Override
protected void onPostExecute(Boolean success) {
// TODO: Do something more useful here
if (success) {
Toast.makeText(MainActivity.this, "Success: " + responseString, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_LONG).show();
}
}
}
Add the fields to the url as parameters.
String phone="phone=234432";
String name="name=John Smith";
String email="email=test@email.com";
Url = new URL("http://www.test.com?"+phone+"&"+name+"&"+email);
Not tested, but it should work in a GET Http request.
//using xml request
String url="http://www.test.com";
String xmlRequest="<message xmlns=\"http://test.com/schemas/ma\"><header></header>"+
"<body><phone>9944556622</phone><name>Mytest name</name><email>mytest@email.com</email>"+"<comments>hay this seems nice</comments></body></message>"
HttpPost httppost = new HttpPost(url);
StringEntity se = new StringEntity(xmlRequest,HTTP.UTF_8);
httppost.setHeader("Content-Type","application/xml");
httppost.setHeader("Accept","application/xml");
httppost.setEntity(se);
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httppost);
StatusLine statusLine = httpResponse.getStatusLine();
HttpClient httpClient = new DefaultHttpClient();
Log.i("sampath","line 139");
HttpPost httpPost = new HttpPost(url);
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("textMessage", msg);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
try {
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
httpPost.setEntity(urlEncodedFormEntity);
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("Firstption caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Secondption caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("Anption given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
//---------------------------------------------------------------------------
Here is the php file
<?php
$message = $_POST['textMessage'];
echo 'working fine'.$message;
$filename="androidmessages.html";
file_put_contents($filename,"Entered Text is:".$message."<br />",FILE_APPEND);
?>