http x-www-form-urlencoded json
x-www-form-urlencoded
// An highlighted block
private String getToken() throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
URI uri = new URI(tokenUrl);
HttpPost httpPost = new HttpPost(uri);
Map<String, String> map = new HashMap<>();
map.put("name", name);
map.put("pwd", pwd);
List<NameValuePair> params = getParamList(map);
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
HttpResponse resp = client.execute(httpPost);
String respStr = EntityUtils.toString(resp.getEntity(), "utf-8");
System.out.println(respStr);
JSONObject object = JSON.parseObject(respStr);
return respStr;
}
private List<NameValuePair> getParamList(Map<String, String> map) {
List<NameValuePair> params = new ArrayList<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
params.add(new NameValuePair() {
@Override
public String getName() {
return entry.getKey();
}
@Override
public String getValue() {
return entry.getValue();
}
});
}
return params;
}
json
private static void order(OrderReqDTO orderReqDTO) throws Exception {
// 连接下订单接口
CloseableHttpClient httpClient = HttpClients.createDefault();
URI uri = new URI(url);
HttpPost httpPost = new HttpPost(uri);
StringEntity entity = new StringEntity(JSON.toJSONString(orderReqDTO), "utf-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
httpPost.addHeader("X-Auth-Token", getToken());
RespDTO respDTO = null;
try {
HttpResponse resp = httpClient.execute(httpPost);
// 请求成功
if (resp.getStatusLine().getStatusCode() == 200) {
String str = EntityUtils.toString(resp.getEntity(), "UTF-8");
System.out.println(str);
respDTO = JSON.parseObject(str, RespDTO.class);
System.out.println(respDTO);
}
} catch (Exception e) {
e.printStackTrace();
}
}