在前面的多数博客中,都有介绍发送HTTP请求的方法,今天出一个极简版本的,平时用来一些连接测试。
Get请求
public static void main(String[] args) throws IOException {
//这个是我的网站域名,啥也没有。各位大佬不要拿我做压力测试谢谢!
String url = "https://www.marsdl.com";
HttpClient httpClient = HttpClients.custom().build();
HttpGet get = new HttpGet(url);
HttpResponse response = httpClient.execute(get);
HttpEntity resp_entity = response.getEntity();
resp_entity.getContent();
String resp_content = EntityUtils.toString(resp_entity,
StandardCharsets.UTF_8);
System.out.println(resp_content);
}
HttpGet实例的对象中可以添加头
get.setHeader("Accept-Encoding", "gzip, deflate");
get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,fr;q=0.6,zh-TW;q=0.4");
get.setHeader("Cache-Control", "no-cache");
get.setHeader("Connection", "keep-alive");
get.setHeader("Host", "www.ximalaya.com");
get.setHeader("Pragma", "no-cache");
post请求
//初始化post请求
String sendUrl = "http://";
HttpPost post = new HttpPost(sendUrl)
post请求,传递body参数
//body参数
JSONObject paramsMap = new JSONObject();
paramsMap.put("playTimes","1");
paramsMap.put("appId", "xxxxxxxxxxx");
paramsMap.put("accountId", "xxxxxxxxxxx");
StringEntity entity = new StringEntity(paramsMap.toJSONString(),
StandardCharsets.UTF_8);
entity.setContentType("application/json");
//生成的body添加到HttpPost中
post.setEntity(entity);
添加post请求的header
post.addHeader("content-type", "application/json");
post.addHeader("Connection", "Keep-Alive");
post.addHeader("Accept", "application/json");
发送请求获得结果
HttpClient httpClient = HttpClients.custom().build();
HttpResponse response = httpClient.execute(post);
String content = EntityUtils.toString(response.getEntity(),
StandardCharsets.UTF_8);
在调用RESTFul接口时,会有一些token验证。目前大多数的加密方式就几种。这几种我总结在这篇博客中,欢迎查看。点击查看博客内容
水平原因可能存在错误,希望指正 chenrui@marsdl.com