当前位置: 代码迷 >> 综合 >> http请求-使用原生的HttpURLConnection
  详细解决方案

http请求-使用原生的HttpURLConnection

热度:106   发布时间:2023-09-29 07:25:56.0

post请求实现: 

    /*** 根据需要发送post请求* @param headers 请求头* @param message 发送数据* @param urlPath 发送接口*/public String senderPostMessage(Map<String,String> headers, String message, String urlPath){HttpURLConnection connection = null;InputStream in = null;OutputStream os = null;try{//根据url地址创建远程连接URL url = new URL(urlPath);//得到一个链接, 强转成httpURLConnection类connection = (HttpURLConnection) url.openConnection();/** 链接方式选择,我们默认POST 从setRequestMethod方法可以有以下其中选择*  <UL>*   <LI>GET*   <LI>POST*   <LI>HEAD*   <LI>OPTIONS*   <LI>PUT*   <LI>DELETE*   <LI>TRACE*  </UL> are legal, subject to protocol restrictions.  The default*  method is GET.*/connection.setRequestMethod("POST");//设置链接服务器的超时时间,当超过这个时间之后不在尝试链接 单位:毫秒connection.setConnectTimeout(15000);/** 设置远程返回的时间:即当链接到远程主机之后 到 发送方得到可读取的数据的时长, 超过设置时间则不在等待返回。抛出:* java.net.SocketTimeoutException。超时为零被解释为无限超时* 单位 :毫秒*/connection.setReadTimeout(6000);/** 当向远程服务器传送数据/写数据时,需要设置为true, 默认为false*/connection.setDoOutput(true);/**  当前向远程服务读取数据时,设置为true,默认为true,可以不设置*/connection.setDoInput(true);/** 设置请求头 可以设置自定义的, 也可以设置一些公认的参数* 常用的有 :  传入参数的格式:Content-Type   可以是已经存在的,也可以是自定义的*             设置鉴权信息:Authorization*/for(Map.Entry<String, String> entry : headers.entrySet()){connection.setRequestProperty(entry.getKey(), entry.getValue());}//获取一个输出流,用于向远程主机发送数据os = connection.getOutputStream();//写入要发送的数据,以字节的方式os.write(message.getBytes("utf-8"));//获取输入流,用于获取远程主机返回结果if(connection.getResponseCode() == 200){in =  connection.getInputStream();/** 将返回数据转换成字符串*/BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));StringBuffer sbf = new StringBuffer();String temp = null;// 循环遍历一行一行读取数据while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}String result = sbf.toString();return result;} else{System.out.println(connection.getResponseCode() + "------" +connection.getResponseMessage());}} catch (Exception e){e.printStackTrace();System.out.println("失败:" + e.getMessage());} finally {//一定要记得关闭流if(in != null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}//断开连接if(connection != null){connection.disconnect();}}return null;}

get请求:

/*** 根据需要发送post请求* @param headers 请求头* @param message 发送数据* @param urlPath 发送接口*/public String sendGetMessage(Map<String,String> headers, String message, String urlPath){HttpURLConnection connection = null;InputStream in = null;OutputStream os = null;try{//根据url地址创建远程连接URL url = new URL(urlPath);//得到一个链接, 强转成httpURLConnection类connection = (HttpURLConnection) url.openConnection();/** 链接方式选择,我们默认GET 从setRequestMethod方法可以有以下其中选择*/connection.setRequestMethod("GET");//设置链接服务器的超时时间,当超过这个时间之后不在尝试链接 单位:毫秒connection.setConnectTimeout(15000);/** 设置远程返回的时间:即当链接到远程主机之后 到 发送方得到可读取的数据的时长, 超过设置时间则不在等待返回。抛出:* java.net.SocketTimeoutException。超时为零被解释为无限超时* 单位 :毫秒*/connection.setReadTimeout(6000);/**  当前向远程服务读取数据时,设置为true,默认为true,可以不设置*/connection.setDoInput(true);/** 设置请求头 可以设置自定义的, 也可以设置一些公认的参数* 常用的有 :  传入参数的格式:Content-Type   可以是已经存在的,也可以是自定义的*             设置鉴权信息:Authorization*/for(Map.Entry<String, String> entry : headers.entrySet()){connection.setRequestProperty(entry.getKey(), entry.getValue());}//获取输入流,用于获取远程主机返回结果if(connection.getResponseCode() == 200){in =  connection.getInputStream();/** 将返回数据转换成字符串*/BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));StringBuffer sbf = new StringBuffer();String temp = null;// 循环遍历一行一行读取数据while ((temp = br.readLine()) != null) {sbf.append(temp);sbf.append("\r\n");}String result = sbf.toString();System.out.println(result);return result;} else {System.out.println("接口返回" +connection.getResponseCode());}} catch (Exception e){e.printStackTrace();} finally {//断开连接if(connection != null){connection.disconnect();}//一定要记得关闭流if(in != null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}}return null;}

 

  相关解决方案