private static String REST_API = "https://127.0.0.1:8080/demo" //需要连接服务的接口
public String addResource(String jsonInfo) throws Exception{
String json =jsonInfo.toString();
ObjectMapper mapper=new ObjectMapper();
URL url =new URL(REST_API);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
OutputStream outputStream =httpURLConnection.getOutputStream();
outputStream.write(mapper.writeValueAsBytes(json));
outputStream.flush();
BufferedReader reader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String result="";
String output;
System.out.println("addResource result is: ");
while ((output = reader.readLine())!=null){
result = result+output;
System.out.println(output);
}
System.out.println("\n");
return result;
}
public static void getAllResource() throws Exception{
URL url = new URL(REST_API+"/getAllResource");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Accept", "application/json");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String output;
System.out.println("getAllResource result is :");
while ((output = reader.readLine())!=null){
System.out.println(output);
}
System.out.println("\n");
}
java http连接其他服务的方式
最新推荐文章于 2024-09-29 16:43:24 发布