一:httpUrlConnection
1.获取HttpURLConnection连接对象
public static HttpURLConnection getHttpURLConnection(String url){
try {
URL httpUrl = new URL(url);
HttpURLConnection urlConnection =(HttpURLConnection)httpUrl.openConnection();
urlConnection.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36");
return urlConnection;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
2.远程调用代码
public void accessLoginUrl(){
String loginUrl = "http://localhost:8989/login/doLogin";
OutputStream outputStream = null;
InputStream inputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
URL url = new URL(loginUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String param = "mobile=" + 13100000000000L + "&password=" + "123456";
outputStream = connection.getOutputStream();
outputStream.write(param.getBytes(StandardCharsets.UTF_8));
outputStream.flush();
inputStream = connection.getInputStream();
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) >= 0){
byteArrayOutputStream.write(buffer, 0, len);
}
String response = byteArrayOutputStream.toString();
ObjectMapper objectMapper = new ObjectMapper()