public class MyHttpPostProjectActivity extends Activity implements OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendPostReqButton;
private Button clearButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
usernameEditText = (EditText) findViewById(R.id.login_username_editText);
passwordEditText = (EditText) findViewById(R.id.login_password_editText);
sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
sendPostReqButton.setOnClickListener(this);
clearButton = (Button) findViewById(R.id.login_clear_button);
clearButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.login_clear_button){
usernameEditText.setText("");
passwordEditText.setText("");
passwordEditText.setCursorVisible(false);
passwordEditText.setFocusable(false);
usernameEditText.setCursorVisible(true);
passwordEditText.setFocusable(true);
}else if(v.getId() == R.id.login_sendPostReq_button){
String givenUsername = usernameEditText.getEditableText().toString();
String givenPassword = passwordEditText.getEditableText().toString();
System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
sendPostRequest(givenUsername, givenPassword);
}
}
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
//Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");
// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
//uniquely separate by the other end.
//To achieve that we use BasicNameValuePair
//Things we need to pass with the POST request
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", 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);
if(result.equals("working")){
Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
}
package com.tutorials.hp.mysqlinsert;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel.
*/
public class Connector {
/*
1.SHALL HELP US ESTABLISH A CONNECTION TO THE NETWORK
2. WE ARE MAKING A POST REQUEST
*/
public static HttpURLConnection connect(String urlAddress) {
try
{
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPERTIES
con.setRequestMethod("POST");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
con.setDoOutput(true);
//RETURN
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataPackager类:
package com.tutorials.hp.mysqlinsert;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel.
* 1.BASICALLY PACKS DATA WE WANNA SEND
*/
public class DataPackager {
String name,position,team;
/*
SECTION 1.RECEIVE ALL DATA WE WANNA SEND
*/
public DataPackager(String name, String position, String team) {
this.name = name;
this.position = position;
this.team = team;
}
/*
SECTION 2
1.PACK THEM INTO A JSON OBJECT
2. READ ALL THIS DATA AND ENCODE IT INTO A FROMAT THAT CAN BE SENT VIA NETWORK
*/
public String packData()
{
JSONObject jo=new JSONObject();
StringBuffer packedData=new StringBuffer();
try
{
jo.put("Name",name);
jo.put("Position",position);
jo.put("Team",team);
Boolean firstValue=true;
Iterator it=jo.keys();
do {
String key=it.next().toString();
String value=jo.get(key).toString();
if(firstValue)
{
firstValue=false;
}else
{
packedData.append("&");
}
packedData.append(URLEncoder.encode(key,"UTF-8"));
packedData.append("=");
packedData.append(URLEncoder.encode(value,"UTF-8"));
}while (it.hasNext());
return packedData.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
发送方类:
package com.tutorials.hp.mysqlinsert;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel and Camposha.com.
* 1.SEND DATA FROM EDITTEXT OVER THE NETWORK
* 2.DO IT IN BACKGROUND THREAD
* 3.READ RESPONSE FROM A SERVER
*/
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText nameTxt,posTxt,teamTxt;
String name,pos,team;
ProgressDialog pd;
/*
1.OUR CONSTRUCTOR
2.RECEIVE CONTEXT,URL ADDRESS AND EDITTEXTS FROM OUR MAINACTIVITY
*/
public Sender(Context c, String urlAddress,EditText...editTexts) {
this.c = c;
this.urlAddress = urlAddress;
//INPUT EDITTEXTS
this.nameTxt=editTexts[0];
this.posTxt=editTexts[1];
this.teamTxt=editTexts[2];
//GET TEXTS FROM EDITEXTS
name=nameTxt.getText().toString();
pos=posTxt.getText().toString();
team=teamTxt.getText().toString();
}
/*
1.SHOW PROGRESS DIALOG WHILE DOWNLOADING DATA
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Send");
pd.setMessage("Sending..Please wait");
pd.show();
}
/*
1.WHERE WE SEND DATA TO NETWORK
2.RETURNS FOR US A STRING
*/
@Override
protected String doInBackground(Void... params) {
return this.send();
}
/*
1. CALLED WHEN JOB IS OVER
2. WE DISMISS OUR PD
3.RECEIVE A STRING FROM DOINBACKGROUND
*/
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response != null)
{
//SUCCESS
Toast.makeText(c,response,Toast.LENGTH_LONG).show();
nameTxt.setText("");
posTxt.setText("");
teamTxt.setText("");
}else
{
//NO SUCCESS
Toast.makeText(c,"Unsuccessful "+response,Toast.LENGTH_LONG).show();
}
}
/*
SEND DATA OVER THE NETWORK
RECEIVE AND RETURN A RESPONSE
*/
private String send()
{
//CONNECT
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
try
{
OutputStream os=con.getOutputStream();
//WRITE
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPackager(name,pos,team).packData());
bw.flush();
//RELEASE RES
bw.close();
os.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode=con.getResponseCode();
if(responseCode==con.HTTP_OK)
{
//GET EXACT RESPONSE
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response=new StringBuffer();
String line;
//READ LINE BY LINE
while ((line=br.readLine()) != null)
{
response.append(line);
}
//RELEASE RES
br.close();
return response.toString();
}else
{
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();