HttpUrlConnection get, post Transmission
No UI operation is written here, and the problem of Chinese garbled characters in get requests is not handled here. If UI operations are performed, we need to explain how to transmit data through get and post in the subthread, other knowledge is not taken into consideration.
Package com. example. httpurlconnectiontest; import java. io. bufferedReader; import java. io. IOException; import java. io. inputStreamReader; import java. io. outputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. protocolException; import java.net. URL; import android. content. context; import android. widget. toast;/*** use HttpUrlConnection to implement get and post data transmission * @ author Admi Nistrator **/public class HttpThread extends Thread {private String url; private String name; private String age; private Context context; public HttpThread (Context context, String url, String name, string age) {this. context = context; this. url = url; this. name = name; this. age = age;} private void doGet () {url = url + "? Username = "+ name +" & password = "+ age; try {URL httpUrl = new URL (url); HttpURLConnection conn = (HttpURLConnection) httpUrl. openConnection (); conn. setRequestMethod ("GET"); conn. setReadTimeout (5000); BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream (); String str; StringBuffer sb = new StringBuffer (); while (str = reader. readLine ())! = Null) {sb. append (str);} System. out. println (sb);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} private void doPost () {try {URL httpUrl = new URL (url); HttpURLConnection conn = (HttpURLConnection) httpUrl. openConnection (); conn. setRequestMethod ("POST"); conn. setReadTimeout (5000); Outpu TStream out = conn. getOutputStream (); String content = "username =" + name + "& password =" + age; out. write (content. getBytes (); BufferedReader reader = new BufferedReader (new InputStreamReader (conn. getInputStream (); String str; StringBuffer sb = new StringBuffer (); while (str = reader. readLine ())! = Null) {sb. append (str);} System. out. println (sb);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (ProtocolException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}@ Overridepublic void run () {// TODO Auto-generated method stub // doGet (); doPost ();}}Call in MainActivity:
String url = "http://115.158.57.173:8080/KuaiDi3/AddUser_servlet";new HttpThread(MainActivity.this,url, "123", "123").start();