Use HttpURLConnection and HttpClient in Android to implement GET and POST requests to access the network
GET in HttpURLConnection
Import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. unsupportedEncodingException; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import java.net. URLEncoder; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. base64; import android. v Iew. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {private EditText content; // declares the private Button button of the edit box object of the input text content; // declares a private Handler handler of the publish Button object; // declare a Handler object private String result = ""; // declare a String private TextView r that represents the displayed content EsultTV; // declare a text box object for Displaying results @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); content = (EditText) findViewById (R. id. content); // obtain the EditText component resultTV = (TextView) findViewById (R. id. result); // obtain the TextView component button = (Button) findViewById (R. id. button); // get the "publish" button component // Add and click the event listener button for the button. setOnClickListener (new O NClickListener () {@ Override public void onClick (View v) {if ("". equals (content. getText (). toString () {Toast. makeText (MainActivity. this, "Enter the content to be published! ", Toast. LENGTH_SHORT ). show (); // display the message prompt return;} // create a new Thread for sending and reading Weibo Information new Thread (new Runnable () {public void run () {send (); // send the text content to the Web server Message m = handler. obtainMessage (); // get a Message handler. sendMessage (m); // send message }}). start (); // enable thread}); // create a Handler Object handler = new Handler () {@ Override public void handleMessage (Message msg) {if (result! = Null) {resultTV. setText (result); // display the obtained content. setText (""); // clear the text box} super. handleMessage (msg) ;}};} public void send () {String target = ""; target = "http: // 192.168.1.66: 8081/blog/index. jsp? Content = "+ base64 (content. getText (). toString (). trim (); // URL of the URL to be accessed; try {url = new url (target); HttpURLConnection urlConn = (HttpURLConnection) URL. openConnection (); // create an HTTP connection InputStreamReader in = new InputStreamReader (urlConn. getInputStream (); // obtain the read content BufferedReader buffer = new BufferedReader (in); // obtain the input stream object String inputLine = null; // read the content of the input stream Row by loop while (inputLine = buffe R. readLine ())! = Null) {result + = inputLine + "\ n";} in. close (); // close the character input stream object urlConn. disconnect (); // disconnect} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace () ;}// encode the String with Base64 public String base64 (String content) {try {content = Base64.encodeToString (content. getBytes ("UTF-8"), Base64.DEFAULT); // base64-encoded string content = URLEncoder. encode (content); // encode the string by URL} catch (UnsupportedEncodingException e) {e. printStackTrace (); // output exception information} return content ;}}
POST in HttpURLConnection
Import java. io. bufferedReader; import java. io. dataOutputStream; import java. io. IOException; import java. io. inputStreamReader; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import java.net. URLEncoder; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onCli CkListener; import android. widget. button; import android. widget. editText; import android. widget. textView; import android. widget. toast; public class MainActivity extends Activity {private EditText nickname; // declares the private EditText content, the edit box object of an input nickname; // declare the private Button button of the edit box object of the input text; // declare the private Handler handler of the publish Button object; // declare a private String result = ""; // declare a private T string representing the displayed content ExtView resultTV; // declare a text box object for Displaying results @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); content = (EditText) findViewById (R. id. content); // obtain the EditText component resultTV = (TextView) findViewById (R. id. result); // obtain the TextView component nickname = (EditText) findViewById (R. id. nickname); // obtain the EditText component button = (Button) fi of the input nickname NdViewById (R. id. button); // get the "publish" button component // Add and click the event listener button for the button. setOnClickListener (new OnClickListener () {@ Override public void onClick (View v) {if ("". equals (nickname. getText (). toString () | "". equals (content. getText (). toString () {Toast. makeText (MainActivity. this, "Enter the complete content! ", Toast. LENGTH_SHORT ). show (); return;} // create a new Thread to obtain the file new Thread (new Runnable () {public void run () {send (); message m = handler. obtainMessage (); // get a Message handler. sendMessage (m); // send message }}). start (); // enable thread}); handler = new Handler () {@ Override public void handleMessage (Message msg) {if (result! = Null) {resultTV. setText (result); // display the obtained content. setText (""); // clear the content edit box nickname. setText (""); // clear the nickname editing box} super. handleMessage (msg) ;}};} public void send () {String target = "http: // 192.168.1.66: 8081/blog/dealPost. jsp "; // target URL url to be submitted; try {url = new URL (target); HttpURLConnection urlConn = (HttpURLConnection) url. openConnection (); // create an HTTP connection urlConn. setRequestMethod ("POST ");// Specify urlConn in POST request mode. setDoInput (true); // write data into the connection urlConn. setDoOutput (true); // reads data from the connection urlConn. setUseCaches (false); // disable caching urlConn. setInstanceFollowRedirects (true); // automatically executes the HTTP redirection urlConn. setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); // you can specify the Content Type DataOutputStream out = new DataOutputStream (urlConn. getOutputStream (); // get the output stream String param = "nickname =" + URLEncoder. enco De (nickname. getText (). toString (), "UTF-8") + "& content =" + URLEncoder. encode (content. getText (). toString (), "UTF-8"); // connects the data to be submitted out. writeBytes (param); // write the data to be passed into the data output stream out. flush (); // output cache out. close (); // close the data output stream // determine whether the response is successful if (urlConn. getResponseCode () = HttpURLConnection. HTTP_ OK) {InputStreamReader in = new InputStreamReader (urlConn. getInputStream (); // obtain the read content BufferedReader buffer = new Buff EredReader (in); // get the input stream object String inputLine = null; while (inputLine = buffer. readLine ())! = Null) {result + = inputLine + "\ n";} in. close (); // close the character input stream} urlConn. disconnect (); // disconnect} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}
HttpClient GET
The only difference between the Get method and the Get method in HttpURLConnection is the send method;
Public void send () {String target = "http: // 192.168.1.66: 8081/blog/deal_httpclient.jsp? Param = get "; // The target address to be submitted HttpClient httpclient = new DefaultHttpClient (); // create an HttpClient object HttpGet httpRequest = new HttpGet (target ); // create an HttpGet connection object HttpResponse httpResponse; try {httpResponse = httpclient.exe cute (httpRequest); // execute the HttpClient request if (httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {result = EntityUtils. toString (httpResponse. getEntity (); // get the returned string} else {result = "Request Failed! ";}} Catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}
HttpClient POST
The send method is the same as the Post method in HttpURLConnection:
Public void send () {String target = "http: // 192.168.1.66: 8081/blog/deal_httpclient.jsp"; // The target address to be submitted: HttpClient httpclient = new DefaultHttpClient (); // create an HttpClient object HttpPost httpRequest = new HttpPost (target); // create an HttpPost object // Save the parameters to be passed to the List set
Params = new ArrayList
(); Params. add (new BasicNameValuePair ("param", "post"); // mark the parameter params. add (new BasicNameValuePair ("nickname", nickname. getText (). toString (); // nickname params. add (new BasicNameValuePair ("content", content. getText (). toString (); // content try {httpRequest. setEntity (new UrlEncodedFormEntity (params, "UTF-8"); // sets the encoding method HttpResponse httpResponse = httpclient.exe cute (httpRequest); // executes the HttpClient request if (httpResp Onse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {// if the request is successful, result + = EntityUtils. toString (httpResponse. getEntity (); // get the returned string} else {result = "the request failed! ";}} Catch (UnsupportedEncodingException e1) {e1.printStackTrace (); // output exception information} catch (ClientProtocolException e) {e. printStackTrace (); // output exception information} catch (IOException e) {e. printStackTrace (); // output exception information }}