模擬 get 請求
package com.woniuxy.httpdemo;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SendGetDemo {
public static void main(String[] args) {
// 準備URL
String urlS = "http://192.168.11.52/Agileone_1.2/index.php";
HttpURLConnection con = null;
InputStream inputStream = null;
//
String key = "Cookie";
String value = "username=admin; password=admin; PHPSESSID=14441ab0acae1ed0cef2f332ba4b0e85";
try {
URL url = new URL(urlS);
// 獲取 HTTP 連接對象
con = (HttpURLConnection) url.openConnection();
// 設置請求頭信息
con.setRequestProperty(key, value);
// 建立連接
con.connect();
// 接收服務器相應內(nèi)容
inputStream = con.getInputStream();
// 長度
int len = -1;
// 容器
byte[] response = new byte[1024];
while ((len = inputStream.read(response)) != -1) {
System.out.println(new String(response, 0, len, "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
con.disconnect();;
}
}
}
模擬 post 請求
package com.woxiuxy.httpdemo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class POSTDemo {
public static void main(String[] args) {
// URL
String URLStr = "http://192.168.10.136/Agileone_1.2/index.php/common/login";
OutputStream os = null;
InputStream is = null;
HttpURLConnection con = null;
// 封裝URL對象
try {
URL url = new URL(URLStr);
// 獲取HTTP連接
con = (HttpURLConnection) url.openConnection();
// 設置請求參數(shù)
// 設置請求方式
con.setRequestMethod("POST");
// 設置Cookie
con.setRequestProperty("Cookie", "PHPSESSID=c05026c0c5131dac7d880ae2a811f339");
// 開啟OutPut流
con.setDoOutput(true);
// 獲取輸出流
os = con.getOutputStream();
// 建立連接
con.connect();
// 定義請求正文
String requestContent = "username=admin&password=admin&savelogin=true";
// 發(fā)送數(shù)據(jù)
os.write(requestContent.getBytes());
// 獲取服務器響應
// 獲取輸入流
is = con.getInputStream();
// 讀取響應數(shù)據(jù)
byte[] content = new byte[1024];
int len = -1;
while ((len = is.read(content)) != -1) {
System.out.print(new String(content, 0, len, "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
is.close();
}
if (con != null) {
con.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
最后編輯于 :
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。