parent
1335eed45a
commit
1960790526
@ -0,0 +1,53 @@
|
||||
package com.zhehekeji.web.service.HttpServe;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class HttpService {
|
||||
public String sendHttp(){
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
/* // 发送 GET 请求
|
||||
String url = "http://example.com/api/getData";
|
||||
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
|
||||
String responseBody = response.getBody();*/
|
||||
|
||||
// 发送 POST 请求
|
||||
String url = "http://example.com/api/postData";
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setContentType(MediaType.APPLICATION_JSON);
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("key1", "value1");
|
||||
body.put("key2", "value2");
|
||||
// 创建Gson对象
|
||||
Gson gson = new Gson();
|
||||
String jsonString = gson.toJson(body);
|
||||
// StringEntity entity = new StringEntity("", headers);
|
||||
restTemplate.postForEntity(url, jsonString, String.class);
|
||||
System.out.println();
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
RestTemplate restTemplate = new RestTemplate();
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("key1", "value1");
|
||||
body.put("key2", "value2");
|
||||
// 创建Gson对象
|
||||
Gson gson = new Gson();
|
||||
String jsonString = gson.toJson(body);
|
||||
// StringEntity entity = new StringEntity("", headers);
|
||||
ResponseEntity<String> response =restTemplate.postForEntity("http://127.0.0.1:8099/api/test/1", jsonString, String.class);
|
||||
System.out.println(jsonString);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue