目的
將Java和HTML語(yǔ)言結(jié)合起來(lái)實(shí)現(xiàn)數(shù)據(jù)的下載
具體內(nèi)容
先建一個(gè)HTML文件,可以下載Sublime Text軟件或者新建一個(gè)文本文檔
<!-- 做一個(gè)表單用于提交用戶的數(shù)據(jù)-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登錄</title>
</head>
<body background="1564315747404.jpeg">
<!-- action 提交內(nèi)容提交到服務(wù)器的哪個(gè)文件中
method 提交方式 get/post
-->
<form action="login.php" method="get">
<!-- 表單內(nèi)容 -->
<br>
<br>
<center>
用戶名:<input type="text" name="user_name">
<br>
<br>
密  碼:<input type="password" name="user_pwd">
<br>
<br>
<input type="submit" value="提交">
</center>
</form>
</body>
</html>
再建一個(gè)PHP文件
<?php
header('Content-type: text/html; charset=GBk');
// 獲取提交的用戶名 get:$_GET post:$_POST
$name=$_POST["user_name"];
$password=$_POST["user_pwd"];
//查詢數(shù)據(jù)庫(kù)
//返回結(jié)果
echo "用戶名:".$name."密碼:".$password;
?>
保存并運(yùn)行
在AndroidStudio里的操作:
1.使用get請(qǐng)求數(shù)據(jù)
public class MyClass {
public static void main(String[] args) throws IOException {
//使用代碼訪問(wèn)服務(wù)器的數(shù)據(jù)
//URL
//1.創(chuàng)建URL
String path="http://127.0.0.1/login.php?"+"user_name=jackson&user_pwd=123";
URL url=new URL(path);
// 獲取連接的對(duì)象
// URLConnection封裝了socket
URLConnection connection=url.openConnection();
//設(shè)置請(qǐng)求方式
HttpURLConnection httpConnection=(HttpURLConnection)connection;
httpConnection.setRequestMethod("GET");
//接收服務(wù)器端的數(shù)據(jù)
InputStream is=connection.getInputStream();
byte[] buf=new byte[1024];
int len;
while ((len=is.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
}
}
2.使用post上傳數(shù)據(jù)
public class MyClass {
public static void main(String[] args) throws IOException {
post();
}
//使用post上傳數(shù)據(jù)
public static void post() throws IOException {
//1.創(chuàng)建URL
URL url=new URL("http://127.0.0.1/login.php");
//2.獲取connection對(duì)象
// URLConnection
// HttpURLConnection 自己需要設(shè)定請(qǐng)求的內(nèi)容
URLConnection connection=url.openConnection();
//3.設(shè)置請(qǐng)求方式為post
((HttpURLConnection) connection).setRequestMethod("POST");
//設(shè)置有輸出流 需要上傳
connection.setDoOutput(true);
//設(shè)置有輸入流 需要下載
connection.setDoInput(true);
//4.準(zhǔn)備上傳的數(shù)據(jù)
String data="user_name=jackson"+"user_pwd=123";
//5.開(kāi)始上傳輸出流對(duì)象
OutputStream os=connection.getOutputStream();
os.write(data.getBytes());
os.flush();
InputStream is=connection.getInputStream();
byte[] buf=new byte[1024];
int len;
while ((len=is.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
}
//下載數(shù)據(jù) get 不帶參數(shù)
public static void getImage() throws IOException {
//URL
URL url=new URL("http://127.0.0.1/1.jpg");
//獲取與服務(wù)器連接的對(duì)象
URLConnection connection=url.openConnection();
//讀取下載的內(nèi)容
InputStream is=connection.getInputStream();
//創(chuàng)建文件保存的位置
FileOutputStream fos=new FileOutputStream("C:/Users/Administrator/AndroidStudioProjects/javaday1/src/main/java/day14/1.jpg");
byte[] buf=new byte[1024];
int len;
while ((len=is.read(buf))!=-1){
fos.write(buf,0,len);
}
}