import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
@Service
@Slf4j
public class TestServiceImpl implements TestService {
@Autowired
private RestTemplate restTemplate;
private final String URL = "http://15.15.82.127:8124/api/test/getData";
private final String USER_NAME = "test";
private final String PASS_WORD = "test123";
第一种方法 //RestTemplate发送POST请求之带header,入参为json格式
@Override
public String getData(){
//1、构建body参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("UserName",USER_NAME);
jsonObject.put("Password",PASS_WORD);
//2、添加请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type","application/json");
//3、组装请求头和参数
HttpEntity formEntity = new HttpEntity(JSON.toJSONString(jsonObject), headers);
//4、发起post请求
ResponseEntity stringResponseEntity = null;
try {
stringResponseEntity = restTemplate.postForEntity(URL, formEntity, String.class);
log.info("ResponseEntity----"+stringResponseEntity);
} catch (RestClientException e) {
e.printStackTrace();
}
//5、获取http状态码
int statusCodeValue = stringResponseEntity.getStatusCodeValue();
log.info("httpCode-----"+statusCodeValue);
//6、获取返回体
String body = stringResponseEntity.getBody();
log.info("body-----"+body);
//7、映射实体类
Wrapper wrapper = JSONObject.parseObject(body, Wrapper.class);
String data = wrapper.getData();
log.info("data-----"+data);
return data;
}
第二种方法
//RestTemplate发送POST请求之formData形式
@Override
public String getData2(){
MultiValueMap reqMap = new LinkedMultiValueMap<>();;
reqMap.add("name","huhansan");
reqMap.add("sex","man");
//.postForEntity(url,请求数据,返回数据类型)
return restTemplate.postForEntity("http://localhost:8888/postwithpara", reqMap, String.class).getBody();
}
}
restTemplate的详细用法可以见此链接
二、Java 使用Httpclient发送post请求 public void post(String url, Map
//创建httppost对象
HttpPost post = new HttpPost(url);
String paramStr = JSON.toJSONString(params);
StringEntity stringEntity = new StringEntity(paramStr, StandardCharsets.UTF_8);
//请求参数
post.setEntity(stringEntity);
//请求头
post.setHeader("Content-Type", "application/json;charset=UTF-8");
String msg = null;
InetAddress ipaddr;
try {
//设置长/短连接 此处为短连接
post.setHeader(HttpHeaders.CONNECTION, HTTP.CONN_CLOSE);
//通过hostname获取本机ip地址
ipaddr = InetAddress.getLocalHost();
post.addHeader(new BasicHeader("API-RemoteIP", ipaddr.getHostAddress()));
//创建httpclient对象发送post请求
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse resp = httpClient.execute(post);
try {
//返回信息
HttpEntity entity = resp.getEntity();
//获取请求状态码
int statusCode = resp.getStatusLine().getStatusCode();
if (entity != null) {
msg = EntityUtils.toString(entity);
//输出日志
logger.info("url:" + url + "参数:" + params.toString() + "返回信息:" + msg);
}
if (statusCode != 200 && statusCode != 302) {
//输出日志
logger.info("url:" + url + "失败信息:" + msg);
}
} finally {
resp.close();
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage(), e);
} finally {
post.reset();
post.releaseConnection();
}
}



