import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
public class HttpClientUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtils.class);
public static String doGET(String url, String username, String password) throws UnsupportedEncodingException {
HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
.setUri(url)
.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder()
.encodeToString((username + ":" + password).getBytes("utf-8")))
.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
.build();
try {
HttpResponse response = client.execute(request);
String json = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("json===>"+json);
return json;
} catch (IOException e) {
LOGGER.error("request fail", e);
}
return null;
}
public static String doPOST(String url) {
// HttpClient client = HttpClients.custom().build();
// HttpUriRequest request = RequestBuilder.post()
// .setUri(url)
//
// .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
// .build();
// try {
// HttpResponse response = client.execute(request);
// String json = EntityUtils.toString(response.getEntity(), "utf-8");
// System.out.println("json===========>" + json);
// return json;
// } catch (IOException e) {
// }
// return null;
public static String doPOST(String url) throws UnsupportedEncodingException {
String body = null;
try
{
HttpClient client = HttpClients.custom().build();
HttpPost post = new HttpPost(url);
post.setHeader("Accept","application/json;charset=utf-8");
JSONObject params = new JSONObject();
params.put("newlogin","epass08");
params.put("bizlogintoken", "9jQcGY89aG4XK5NDiOrZcp3s8SbVKYuYKV_eqlxRRm9MDPlXnA8GSG4wfC5sPtSmyN5hd_3TRJ2W2wDrxySngQ");
// 传值时传递的是json字符串,这样的好处是在服务端无需建立参数模型,直接接收String,便于后期维护。
StringEntity stringEntity = new StringEntity(params.toJSONString(),"utf-8");
post.setEntity(stringEntity);
HttpResponse response = client.execute(post);
System.out.println("响应码:"+response.getStatusLine());
body = EntityUtils.toString(response.getEntity());
System.out.println("响应body体:"+body);
} catch (Exception e) {
LOGGER.info("request failed {}", e);
}
return body;
}
public static void main(String[] args) throws UnsupportedEncodingException {
String username = "admin";
String password = "f2224d2c7f9a3c126baa3b90166daeaf";
String getUrl = "";
String postUrl = "";
// doGET(getUrl, username, password);
doPOST(postUrl);
}
}