通过HttpURLConnection访问别人的接口地址
import java.io.*;
import java.net.*;
public class HttpTest {
public static void main(String[] args) throws Exception {
try{
String jsonStr = "{\"username\":\"admin\", \"password\":\"wf2010\"}";
// 创建连接对象
URL url = new URL("http://192.168.10.19/dev-api/login");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
// 开始输入流并写入参数
OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
writer.write(jsonStr);
writer.flush();
writer.close();
outputStream.close();
// 获取返回结果
int responseCode = connection.getResponseCode();
InputStream inputStream;
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
// 读取返回内容
StringBuilder stringBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
reader.close();
System.out.println("Response Code : " + responseCode);
System.out.println("Response Message : " + stringBuilder.toString());
}catch (Exception e){
e.printStackTrace();
}
}
}