package com.example.util;
import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* url "127.0.0.1:9528/registration_server/api/getToken"
*body 参数参数
* HttpClient工具类
*/
public class HttpUtil {
public static String doPost(String url,String action ,String body) {
String result = null;
HttpClient client = HttpClients.createDefault();
URIBuilder builder = new URIBuilder();
URI uri = null;
try {
uri = builder.setScheme("http")
.setHost(url) // "127.0.0.1:9528"
.setPath(action) //"/registration_server/api/getToken"
.build();
HttpPost post = new HttpPost(uri);
//设置请求头
post.setHeader("Content-Type", "application/json");
// String body = "{\"channelNo\": \"888888\",\"password\": \"123456\"}";
//设置请求体
post.setEntity(new StringEntity(body));
//获取返回信息
HttpResponse response = client.execute(post);
HttpEntity entity=response.getEntity();
// String rtn=EntityUtils.toString(entity);
// JSONObject obj=(JSONObject) JSONObject.parse(rtn);
// System.out.println("data======"+obj.get("data"));
// result =(String) obj.get("data");
return EntityUtils.toString(entity,"utf-8");
} catch (Exception e) {
System.out.println("接口请求失败"+e.getStackTrace());
}
// System.out.println(result);
// return result;
return "";
}
}