「SpringBoot」 Java中如何封装Http请求

前言本文中的内容其实严格来说不算springboot里面的特性,属于JAVA基础,只是我在项目中遇到了,特归纳总结一下 。
HTTP请求封装目前JAVA对于HTTP封装主要有三种方式:
1. JAVA原生封装
2. HttpClient 3.X /HttpClient4.X
3. Spring RestTemplate
http请求过程如下:
GET:1、创建远程连接2、设置连接方式(get、post、put 。。。)3、设置连接超时时间4、设置响应读取时间5、发起请求6、获取请求数据7、关闭连接POST:1、创建远程连接2、设置连接方式(get、post、put 。。。)3、设置连接超时时间4、设置响应读取时间5、当向远程服务器传送数据/写数据时,需要设置为true(setDoOutput)6、当前向远程服务读取数据时,设置为true,该参数可有可无(setDoInput)7、设置传入参数的格式:(setRequestProperty)8、设置鉴权信息:Authorization:(setRequestProperty)9、设置参数10、发起请求11、获取请求数据12、关闭连接JAVA原生:/** * http get请求 * @param httpUrl 链接 * @return 响应数据 */public static String doGet(String httpUrl){//链接HttpURLConnection connection=null;InputStream is=null;BufferedReader br = null;StringBuffer result=new StringBuffer();try {//创建连接URL url=new URL(httpUrl);connection= (HttpURLConnection) url.openConnection();//设置请求方式connection.setRequestMethod("GET");//设置连接超时时间connection.setConnectTimeout(15000);//设置读取超时时间connection.setReadTimeout(15000);//开始连接connection.connect();//获取响应数据if(connection.getResponseCode()==200){//获取返回的数据is=connection.getInputStream();if(is!=null){br=new BufferedReader(new InputStreamReader(is,"UTF-8"));String temp = null;while ((temp=br.readLine())!=null){result.Append(temp);}}}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(br!=null){try {br.close();} catch (IOException e) {e.printStackTrace();}}if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}connection.disconnect();// 关闭远程连接}return result.toString();}/*** post请求* @param httpUrl 链接* @param param 参数* @return*/public static String doPost(String httpUrl, @Nullable String param) {StringBuffer result=new StringBuffer();//连接HttpURLConnection connection=null;OutputStream os=null;InputStream is=null;BufferedReader br=null;try {//创建连接对象URL url=new URL(httpUrl);//创建连接connection= (HttpURLConnection) url.openConnection();//设置请求方法connection.setRequestMethod("POST");//设置连接超时时间connection.setConnectTimeout(15000);//设置读取超时时间connection.setReadTimeout(15000);//设置是否可读取connection.setDoOutput(true);//设置响应是否可读取connection.setDoInput(true);//设置参数类型connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//拼装参数if(param!=null&&!param.equals("")){//设置参数os=connection.getOutputStream();//拼装参数os.write(param.getBytes("UTF-8"));}//设置权限//设置请求头等//开启连接//connection.connect();//读取响应if(connection.getResponseCode()==200){is=connection.getInputStream();if(is!=null){br=new BufferedReader(new InputStreamReader(is,"UTF-8"));String temp=null;if((temp=br.readLine())!=null){result.append(temp);}}}//关闭连接} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally {if(br!=null){try {br.close();} catch (IOException e) {e.printStackTrace();}}if(os!=null){try {os.close();} catch (IOException e) {e.printStackTrace();}}if(is!=null){try {is.close();} catch (IOException e) {e.printStackTrace();}}//关闭连接connection.disconnect();}return result.toString();}HttpCLient4.Xhttpclient有很多版本,目前最新的版本是4.X了,所以推荐使用4.x的方式进行封装
public static String doGet(String url) {CloseableHttpClient httpClient = null;CloseableHttpResponse response = null;String result = "";try {// 通过址默认配置创建一个httpClient实例httpClient = HttpClients.createDefault();// 创建httpGet远程连接实例HttpGet httpGet = new HttpGet(url);// 设置请求头信息,鉴权httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");// 设置配置请求参数RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间.setConnectionRequestTimeout(35000)// 请求超时时间.setSocketTimeout(60000)// 数据读取超时时间.build();// 为httpGet实例设置配置httpGet.setConfig(requestConfig);// 执行get请求得到返回对象response = httpClient.execute(httpGet);// 通过返回对象获取返回数据HttpEntity entity = response.getEntity();// 通过EntityUtils中的toString方法将结果转换为字符串result = EntityUtils.toString(entity);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭资源if (null != response) {try {response.close();} catch (IOException e) {e.printStackTrace();}}if (null != httpClient) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}return result;}public static String doPost(String url, Map<String, Object> paramMap) {CloseableHttpClient httpClient = null;CloseableHttpResponse httpResponse = null;String result = "";// 创建httpClient实例httpClient = HttpClients.createDefault();// 创建httpPost远程连接实例HttpPost httpPost = new HttpPost(url);// 配置请求参数实例RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间.setConnectionRequestTimeout(35000)// 设置连接请求超时时间.setSocketTimeout(60000)// 设置读取数据连接超时时间.build();// 为httpPost实例设置配置httpPost.setConfig(requestConfig);// 设置请求头httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");// 封装post请求参数if (null != paramMap && paramMap.size() > 0) {List<NameValuePair> nvps = new ArrayList<NameValuePair>();// 通过map集成entrySet方法获取entitySet<Entry<String, Object>> entrySet = paramMap.entrySet();// 循环遍历,获取迭代器Iterator<Entry<String, Object>> iterator = entrySet.iterator();while (iterator.hasNext()) {Entry<String, Object> mapEntry = iterator.next();nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));}// 为httpPost设置封装好的请求参数try {httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}}try {// httpClient对象执行post请求,并返回响应参数对象httpResponse = httpClient.execute(httpPost);// 从响应对象中获取响应内容HttpEntity entity = httpResponse.getEntity();result = EntityUtils.toString(entity);} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {// 关闭资源if (null != httpResponse) {try {httpResponse.close();} catch (IOException e) {e.printStackTrace();}}if (null != httpClient) {try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}return result;}


推荐阅读