Copy codeThe Code is as follows: package com. hl;
Import java. io. BufferedReader;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. InputStreamReader;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. Iterator;
Import java. util. Map;
Import java. util. Set;
Import org. apache. http. HttpEntity;
Import org. apache. http. HttpResponse;
Import org. apache. http. client. entity. UrlEncodedFormEntity;
Import org. apache. http. client. methods. HttpPost;
Import org. apache. http. impl. client. DefaultHttpClient;
Import org. apache. http. message. BasicNameValuePair;
Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
Import android. widget. EditText;
Import android. widget. TextView;
Public class SimplePOST extends Activity {
Private TextView show;
Private EditText txt;
Private Button btn;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Show = (TextView) findViewById (R. id. show );
Txt = (edittext=findviewbyid(r.id.txt );
Btn = (Button) findViewById (R. id. btn );
Btn. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
Dopost (txt. getText (). toString ());
}
});
}
Private void dopost (String val ){
// Encapsulate data
Map <String, String> parmas = new HashMap <String, String> ();
Parmas. put ("name", val );
DefaultHttpClient client = new DefaultHttpClient (); // http client
HttpPost httpPost = new HttpPost ("http://mhycoe.com/test/post.php ");
ArrayList <BasicNameValuePair> pairs = new ArrayList <BasicNameValuePair> ();
If (parmas! = Null ){
Set <String> keys = parmas. keySet ();
For (Iterator <String> I = keys. iterator (); I. hasNext ();){
String key = (String) I. next ();
Pairs. add (new BasicNameValuePair (key, parmas. get (key )));
}
}
Try {
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity (pairs, "UTF-8 ");
/*
* Put POST data into an HTTP request
*/
HttpPost. setEntity (p_entity );
/*
* Send an actual http post request
*/
HttpResponse response = client.exe cute (httpPost );
HttpEntity entity = response. getEntity ();
InputStream content = entity. getContent ();
String returnConnection = convertStreamToString (content );
Show. setText (returnConnection );
} Catch (IllegalStateException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
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 ();
}
}