赞
踩
引入的依赖包,也可以去 阿里仓库下载 ————>前往阿里云仓库
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <version>3.7</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context</artifactId>
- <version>5.2.1.RELEASE</version>
- </dependency>
一个Get Post请求的java代码
-
- import org.apache.commons.lang3.StringUtils;
- import org.springframework.util.StreamUtils;
-
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.nio.charset.Charset;
- import java.util.Map;
-
- public class HttpUtil {
-
- /**
- * post请求
- * @param urlStr
- * @param param
- * @param userAgent
- * @return
- */
- public static String httpPost(String urlStr,String param,String userAgent){
- try {
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setReadTimeout(5000);
- conn.setConnectTimeout(60 * 1000);
- if(StringUtils.isNotBlank(userAgent)){
- conn.setRequestProperty("User-Agent",
- userAgent);
- }
- conn.setUseCaches(false);
- conn.setDoInput(true);
- conn.setDoOutput(true);
- BufferedOutputStream out = new BufferedOutputStream(conn
- .getOutputStream());
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(),"utf-8"));
- bw.write(param);
- bw.flush();
- bw.close();
-
- if (conn.getResponseCode()==200){
- BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
- String tempStr = null;
- String str = "";
- while ((tempStr=br.readLine())!=null){
- str +=tempStr;
- }
- br.close();
- return str;
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return null;
- }
- /**
- * post请求
- * @param urlStr
- * @param xmlParam
- * @return
- */
- public static String httpPost(String urlStr,String xmlParam){
- return httpPost(urlStr,xmlParam,null);
- }
-
-
- /**
- * 调用外部接口,并返回响应结果
- * @param httpUrl
- * @param params
- * @return
- * @throws Exception
- */
- public static String sendHttpPostRequest(String httpUrl, Map<String, String> params) throws Exception{
-
- URL url = new URL(httpUrl);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setDoOutput(true);
-
- if(params != null && params.size() > 0){
- StringBuilder sb = new StringBuilder();
- for(Map.Entry<String, String> entry : params.entrySet()){
- sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
- }
- conn.getOutputStream().write(sb.substring(1).getBytes("utf-8"));
- }
- conn.connect();
- String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
-
- conn.disconnect();
- return responseContent;
- }
-
- public static String sendHttpGetRequest(String httpUrl, Map<String, String> params) throws Exception{
-
- try {
- if(params != null && params.size() > 0){
- StringBuilder sb = new StringBuilder();
- for(Map.Entry<String, String> entry : params.entrySet()){
- sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
- }
- sb = new StringBuilder(sb.substring(1));
- if(httpUrl.contains("?")){
- httpUrl += "&"+sb.toString();
- }else{
- httpUrl += "?"+sb.toString();
- }
- }
- URL url = new URL(httpUrl);
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.setRequestMethod("GET");
- conn.setDoOutput(true);
- conn.connect();
- String responseContent = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("utf-8"));
- conn.disconnect();
- return responseContent;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
-
-
- //获得网络路径
- public static InputStream getImageStream(String url) throws Exception{
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setReadTimeout(5000);
- connection.setConnectTimeout(5000);
- connection.setRequestMethod("GET");
- connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- return connection.getInputStream();
- }else{
- throw new Exception("响应状态:" + connection.getResponseCode() + "\n" +
- "响应内容:" + connection.getResponseMessage());
- }
- }
-
- //判断当前请求是否有效
- public static boolean sendGetRequestAck(String url) throws Exception{
- HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
- connection.setReadTimeout(5000);
- connection.setConnectTimeout(5000);
- connection.setRequestMethod("GET");
- connection.addRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36");
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- return true;
- }else{
- return false;
- }
- }
-
- //把字节流转换成字节数组
- public static byte[] toByteArray(InputStream input) {
- try {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024*4];
- int n = 0;
- while (-1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- }
- return output.toByteArray();
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- //把字节数组转换成字节流
- public static InputStream toInputStream(byte[] bytes){
- return new ByteArrayInputStream(bytes);
- }
-
- //字节流转换字节流
- public static InputStream toInputStream(InputStream input){
- return toInputStream(toByteArray(input));
- }
- }
-
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。