1 new Thread(){ 2 @Override 3 public void run() { 4 try { 5 //1.有了网络地址,得到URL 6 String urlPath = "http://192.168.35.10:8080/login/login?username=" + username + "&pwd=" + pwd; 7 URL url = new URL(urlPath); 8 //2.打开Http连接 9 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 10 //3.设置请求方式 11 conn.setRequestMethod("GET"); 12 //4.判断响应码 13 if(conn.getResponseCode() == 200){ 14 //5.读取输入流 15 InputStream is = conn.getInputStream(); 16 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 17 final String result = reader.readLine(); 18 runOnUiThread(new Runnable() { 19 @Override 20 public void run() { 21 Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); 22 } 23 }); 24 } 25 } catch (Exception e) { 26 e.printStackTrace(); 27 } 28 } 29 }.start();
_______________________________________________________________________________________________________________
new Thread(){ @Override public void run() { try { //1.有了网络地址,得到URL String urlPath = "http://192.168.35.10:8080/loginPost/login"; URL url = new URL(urlPath); //2.打开Http连接 HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); //3.设置请求方式 conn.setRequestMethod("POST"); //这里有两个请求头 //1.告诉服务器 我们是一个form表单 //计算参数的字符串的长度 String params = "username=" + username + "&pwd=" + pwd; conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", params.length() + ""); //********向服务器提交数据OutputStream******** //安卓下HtttpURLConnection的输出流开关默认是关闭的 conn.setDoOutput(true); conn.getOutputStream().write(params.getBytes()); //**************** //4.判断响应码 if(conn.getResponseCode() == 200){ //5.读取输入流 InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final String result = reader.readLine(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show(); } }); } } catch (Exception e) { e.printStackTrace(); } } }.start();
浙公网安备 33010602011771号