代码中发起请求

代码中发起get或post请求
1.java原生的发起请求,通过IO流进行数据的写入写出,
String strUrl = “xxx”;
try{
//建立连接
URL url = new URL(strUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
}catch (Exception e){
e.printStackTrace();
}
2.通过httpclient开源框架建立连接
HTTPClient可以理解为浏览器,但不是浏览器,想发起请求,必须先有浏览器,再确定是get还是post请求,是否有参数.
发起请求时,请求头中content-type必须要确定,确定要传输的数据是什么类型-application/json,Multipart等,还要设置字符类型(charset),不然会有乱码.
//创建浏览器
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
//发起请求
HttpPost httpPost = new HttpPost(“xxxxx”);
//设置请求头,和将参数set到请求实体中
httpPost.setHeader(“Content-Type”,“application/json;charset=utf8”);
User user = new User();
//转为json串
String jsonUser = JSON.toJSONString(user );
StringEntity StringEntity = new StringEntity(jsonUser,“UTF-8”);
httpPost.setEntity(StringEntity);
//相应模型
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity str = response.getEntity();
}catch (Exception e){
e.printStackTrace();
}
//关闭资源

你可能感兴趣的:(代码中发起请求)