当前位置: 首页 > news >正文

java实现Http请求方式的几种常见方式

背景

在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。若是普通java工程推荐使用OkHttpClient,若是spring工程推荐使用RestTemplate。,若是springcloud微服务可以用openFeign或Dubbo

在Java项目中调用第三方接口的方式有:

1、通过JDK网络类Java.net.HttpURLConnection;

2、通过common封装好的HttpClient;

3、通过Apache封装好的CloseableHttpClient;

4、通过SpringBoot-RestTemplate;

5、通过Feign服务调用

一、Java调用第三方http接口几种方式总结

1. 通过JDK网络类Java.net.HttpURLConnection

比较原始的一种调用做法,这里把get请求和post请求都统一放在一个方法里面。
实现过程:

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、关闭连接

直接上代码: 

import org.springframework.lang.Nullable;import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;public class HttpURLConnectionUtil {/*** 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.setReadTimeout(15000);//开始连接connection.connect();//获取响应数据if (connection.getResponseCode() == 200) {//获取返回的数据is = connection.getInputStream();if (null != is) {br = new BufferedReader(new InputStreamReader(is, "UTF-8"));String temp = null;while (null != (temp = br.readLine())) {result.append(temp);}}}} catch (IOException e) {e.printStackTrace();} finally {if (null != br) {try {br.close();} catch (IOException e) {e.printStackTrace();}}if (null != is) {try {is.close();} catch (IOException e) {e.printStackTrace();}}//关闭远程连接connection.disconnect();}return result.toString();}/*** Http 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);//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个//设置是否可读取connection.setDoOutput(true);connection.setDoInput(true);//设置通用的请求属性connection.setRequestProperty("accept", "*/*");connection.setRequestProperty("connection", "Keep-Alive");connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");//拼装参数if (null != param && param.equals("")) {//设置参数os = connection.getOutputStream();//拼装参数os.write(param.getBytes("UTF-8"));}//设置权限//设置请求头等//开启连接//connection.connect();//读取响应if (connection.getResponseCode() == 200) {is = connection.getInputStream();if (null != is) {br = new BufferedReader(new InputStreamReader(is, "GBK"));String temp = null;while (null != (temp = br.readLine())) {result.append(temp);result.append("\r\n");}}}} 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();}public static void main(String[] args) {String message = doPost("https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "");System.out.println(message);}
}

运行结果: 

2. 通过apache common封装好的HttpClient

httpClient的get或post请求方式步骤:

1.生成一个HttpClient对象并设置相应的参数;
2.生成一个GetMethod对象或PostMethod并设置响应的参数;
3.用HttpClient生成的对象来执行GetMethod生成的Get方法;
4.处理响应状态码;
5.若响应正常,处理HTTP响应内容;
6.释放连接。

<!--HttpClient-->
<dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version>
</dependency><!--fastjson-->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.32</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;import java.io.IOException;/*** @Author allen* @Description TODO* @Date 2023-10-18 18:25* @Version 1.0*/
public class HttpClientUtil {/*** httpClient的get请求方式* 使用GetMethod来访问一个URL对应的网页实现步骤:* 1.生成一个HttpClient对象并设置相应的参数;* 2.生成一个GetMethod对象并设置响应的参数;* 3.用HttpClient生成的对象来执行GetMethod生成的Get方法;* 4.处理响应状态码;* 5.若响应正常,处理HTTP响应内容;* 6.释放连接。** @param url* @param charset* @return*/public static String doGet(String url, String charset) {//1.生成HttpClient对象并设置参数HttpClient httpClient = new HttpClient();//设置Http连接超时为5秒httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);//2.生成GetMethod对象并设置参数GetMethod getMethod = new GetMethod(url);//设置get请求超时为5秒getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//设置请求重试处理,用的是默认的重试处理:请求三次getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());String response = "";//3.执行HTTP GET 请求try {int statusCode = httpClient.executeMethod(getMethod);//4.判断访问的状态码if (statusCode != HttpStatus.SC_OK) {System.err.println("请求出错:" + getMethod.getStatusLine());}//5.处理HTTP响应内容//HTTP响应头部信息,这里简单打印Header[] headers = getMethod.getResponseHeaders();for (Header h : headers) {System.out.println(h.getName() + "---------------" + h.getValue());}//读取HTTP响应内容,这里简单打印网页内容//读取为字节数组byte[] responseBody = getMethod.getResponseBody();response = new String(responseBody, charset);System.out.println("-----------response:" + response);//读取为InputStream,在网页内容数据量大时候推荐使用//InputStream response = getMethod.getResponseBodyAsStream();} catch (HttpException e) {//发生致命的异常,可能是协议不对或者返回的内容有问题System.out.println("请检查输入的URL!");e.printStackTrace();} catch (IOException e) {//发生网络异常System.out.println("发生网络异常!");} finally {//6.释放连接getMethod.releaseConnection();}return response;}/*** post请求** @param url* @param json* @return*/public static String doPost(String url, JSONObject json) {HttpClient httpClient = new HttpClient();PostMethod postMethod = new PostMethod(url);postMethod.addRequestHeader("accept", "*/*");postMethod.addRequestHeader("connection", "Keep-Alive");//设置json格式传送postMethod.addRequestHeader("Content-Type", "application/json;charset=GBK");//必须设置下面这个HeaderpostMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");//添加请求参数postMethod.addParameter("commentId", json.getString("commentId"));String res = "";try {int code = httpClient.executeMethod(postMethod);if (code == 200) {res = postMethod.getResponseBodyAsString();System.out.println(res);}} catch (IOException e) {e.printStackTrace();}return res;}public static void main(String[] args) {System.out.println(doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "GBK"));System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");System.out.println("-----------分割线------------");JSONObject jsonObject = new JSONObject();jsonObject.put("commentId", "13026194071");System.out.println(doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", jsonObject));}
}

3. 通过Apache封装好的CloseableHttpClient

CloseableHttpClient是在HttpClient的基础上修改更新而来的,这里还涉及到请求头token的设置(请求验证),利用fastjson转换请求或返回结果字符串为json格式,当然上面两种方式也是可以设置请求头token、json的,这里只在下面说明。

导入如下jar包:

<!--CloseableHttpClient-->
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version>
</dependency><!--fastjson-->
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.32</version>
</dependency>
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;import java.io.IOException;/*** @Author allen* @Description TODO* @Date 2023-10-18 18:31* @Version 1.0*/
public class CloseableHttpClientUtil {private static String tokenString = "";private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";private static CloseableHttpClient httpClient = null;/*** 以get方式调用第三方接口* @param url* @param token* @return*/public static String doGet(String url, String token) {//创建HttpClient对象CloseableHttpClient httpClient = HttpClientBuilder.create().build();HttpGet httpGet = new HttpGet(url);if (null != tokenString && !tokenString.equals("")) {tokenString = getToken();}//api_gateway_auth_token自定义header头,用于token验证使用httpGet.addHeader("api_gateway_auth_token",tokenString);httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");try {HttpResponse response = httpClient.execute(httpGet);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//返回json格式String res = EntityUtils.toString(response.getEntity());return res;}} catch (IOException e) {e.printStackTrace();}return null;}/*** 以post方式调用第三方接口* @param url* @param json* @return*/public static String doPost(String url, JSONObject json) {if (null == httpClient) {httpClient = HttpClientBuilder.create().build();}HttpPost httpPost = new HttpPost(url);if (null != tokenString && tokenString.equals("")) {tokenString = getToken();}//api_gateway_auth_token自定义header头,用于token验证使用httpPost.addHeader("api_gateway_auth_token", tokenString);httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");try {StringEntity se = new StringEntity(json.toString());se.setContentEncoding("UTF-8");//发送json数据需要设置contentTypese.setContentType("application/x-www-form-urlencoded");//设置请求参数httpPost.setEntity(se);HttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {//返回json格式String res = EntityUtils.toString(response.getEntity());return res;}} catch (IOException e) {e.printStackTrace();} finally {if (httpClient != null){try {httpClient.close();} catch (IOException e) {e.printStackTrace();}}}return null;}/*** 获取第三方接口的token*/public static String getToken() {String token = "";JSONObject object = new JSONObject();object.put("appid", "appid");object.put("secretkey", "secretkey");if (null == httpClient) {httpClient = HttpClientBuilder.create().build();}HttpPost httpPost = new HttpPost("http://localhost/login");httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");try {StringEntity se = new StringEntity(object.toString());se.setContentEncoding("UTF-8");//发送json数据需要设置contentTypese.setContentType("application/x-www-form-urlencoded");//设置请求参数httpPost.setEntity(se);HttpResponse response = httpClient.execute(httpPost);//这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类//ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);//把response转为jsonObjectJSONObject result = (JSONObject) JSONObject.parseObject(String.valueOf(response));if (result.containsKey("token")) {token = result.getString("token");}} catch (IOException e) {e.printStackTrace();}return token;}/*** 测试*/public static void test(String telephone) {JSONObject object = new JSONObject();object.put("telephone", telephone);//首先获取tokentokenString = getToken();String response = doPost("http://localhost/searchUrl", object);//如果返回的结果是list形式的,需要使用JSONObject.parseArray转换//List<Result> list = JSONObject.parseArray(response, Result.class);System.out.println(response);}public static void main(String[] args) {test("12345678910");}
}

4. 通过SpringBoot-RestTemplate

springBoot-RestTemple是上面三种方式的集大成者,代码编写更加简单,目前可以采用的调用第三方接口有:

delete() 在特定的URL上对资源执行HTTP DELETE操作
exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
postForLocation() POST 数据到一个URL,返回新创建资源的URL
put() PUT 资源到特定的URL

首先导入springboot的web包

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version></parent><dependencies><!--CloseableHttpClient--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.2</version></dependency><!--spring restTemplate--><!-- @ConfigurationProperties annotation processing (metadata for IDEs)生成spring-configuration-metadata.json类,需要引入此类--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><exclusions><exclusion><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jetty</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>

在启动类同包下创建RestTemplateConfig.java类

import java.io.IOException;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;import com.fasterxml.jackson.databind.ObjectMapper;/*** @Author allen* @Description TODO* @Date 2023-10-18 18:41* @Version 1.0*/
@Configuration
public class RestTemplateConfig {@Autowiredprivate ObjectMapper objectMapper;@Beanpublic RestTemplate restTemplate() {RestTemplate template = new RestTemplate();// 设置 http 超时时间HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();// 获取链接超时时间httpRequestFactory.setConnectionRequestTimeout(6000);// 链接超时时间 6ShttpRequestFactory.setConnectTimeout(6000);// 读取超时 6ShttpRequestFactory.setReadTimeout(6000);template.setRequestFactory(httpRequestFactory);//		template.getInterceptors().add((request,body,execution) -> {
//			final RequestAttributes requestAttributes=RequestContextHolder.getRequestAttributes();
//			if(requestAttributes!=null&&requestAttributes instanceof ServletRequestAttributes){
//				final HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
//				request.getHeaders().add("token", servletRequest.getHeader("token"));
//				request.getHeaders().add("location", servletRequest.getHeader("location"));
//				request.getHeaders().add("appId", servletRequest.getHeader("appId"));
//			}
//			return execution.execute(request, body);
//		});template.setErrorHandler(new ResponseErrorHandler() {@Overridepublic boolean hasError(ClientHttpResponse response) throws IOException {System.out.println("RestTemplateConfig------------------hasError");return response.getRawStatusCode() >= 400;}@Overridepublic void handleError(ClientHttpResponse response) throws IOException {System.out.println("RestTemplateConfig----------handleError--------异常");String result = objectMapper.readValue(response.getBody(), String.class);throw new RuntimeException(result);}});//        template.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));return template;}}

然后在Service类(RestTemplateToInterface )中注入使用

具体代码如下:

import com.alibaba.fastjson.JSONObject;
import com.swordfall.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;@Service
public class RestTemplateToInterface {@Autowiredprivate RestTemplate restTemplate;/*** 以get方式请求第三方http接口 getForEntity* @param url* @return*/public User doGetWith1(String url){ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);User user = responseEntity.getBody();return user;}/*** 以get方式请求第三方http接口 getForObject* 返回值返回的是响应体,省去了我们再去getBody()* @param url* @return*/public User doGetWith2(String url){User user  = restTemplate.getForObject(url, User.class);return user;}/*** 以post方式请求第三方http接口 postForEntity* @param url* @return*/public String doPostWith1(String url){User user = new User("小白", 20);ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);String body = responseEntity.getBody();return body;}/*** 以post方式请求第三方http接口 postForEntity* @param url* @return*/public String doPostWith2(String url){User user = new User("小白", 20);String body = restTemplate.postForObject(url, user, String.class);return body;}/*** exchange* @return*/public String doExchange(String url, Integer age, String name){//header参数HttpHeaders headers = new HttpHeaders();String token = "asdfaf2322";headers.add("authorization", token);headers.setContentType(MediaType.APPLICATION_JSON);//放入body中的json参数JSONObject obj = new JSONObject();obj.put("age", age);obj.put("name", name);//组装HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);String body = responseEntity.getBody();return body;}
}

5 通过okhttp

应大家的响应,okhttp 现在也是蛮流行的,基于手机端很火,这里分享一下OkHttpClient客户端,业务代码get、post请求直接调用就好哈。

pom文件引入依赖包

<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>3.10.0</version>
</dependency>
@Slf4j
public class OkHttpClient {private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");private volatile static okhttp3.OkHttpClient client;private static final int MAX_IDLE_CONNECTION = Integer.parseInt(ConfigManager.get("httpclient.max_idle_connection"));private static final long KEEP_ALIVE_DURATION = Long.parseLong(ConfigManager.get("httpclient.keep_alive_duration"));private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));/*** 单例模式(双重检查模式) 获取类实例** @return client*/private static okhttp3.OkHttpClient getInstance() {if (client == null) {synchronized (okhttp3.OkHttpClient.class) {if (client == null) {client = new okhttp3.OkHttpClient.Builder().connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION,TimeUnit.MINUTES)).build();}}}return client;}public static String syncPost(String url, String json) throws IOException {RequestBody body = RequestBody.create(JSON, json);Request request = new Request.Builder().url(url).post(body).build();try {Response response = OkHttpClient.getInstance().newCall(request).execute();if (response.isSuccessful()) {String result = response.body().string();log.info("syncPost response = {}, responseBody= {}", response, result);return result;}String result = response.body().string();log.info("syncPost response = {}, responseBody= {}", response, result);throw new IOException("三方接口返回http状态码为" + response.code());} catch (Exception e) {log.error("syncPost() url:{} have a ecxeption {}", url, e);throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());}}public static String syncGet(String url, Map<String, Object> headParamsMap) throws IOException {Request request;final Request.Builder builder = new Request.Builder().url(url);try {if (!CollectionUtils.isEmpty(headParamsMap)) {final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet().iterator();while (iterator.hasNext()) {final Map.Entry<String, Object> entry = iterator.next();builder.addHeader(entry.getKey(), (String) entry.getValue());}}request = builder.build();Response response = OkHttpClient.getInstance().newCall(request).execute();String result = response.body().string();log.info("syncGet response = {},responseBody= {}", response, result);if (!response.isSuccessful()) {throw new IOException("三方接口返回http状态码为" + response.code());}return result;} catch (Exception e) {log.error("remote interface url:{} have a ecxeption {}", url, e);throw new RuntimeException("三方接口返回异常");}}}

https://blog.csdn.net/qq_16504067/article/details/121114404

6 通过openFeign

可以参考博主的这篇文章

Feign实战-Springboot集成OpenFeign Demo以及参数详解_Alex_81D的博客-CSDN博客

二、方案扩展

我用的这个:

HttpUtils如下:
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.UnsupportedCharsetException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;/*** Http tool class*/
public class HttpUtils {public static String INTERFACE_CALL_ERROR = "接口调用错误";private static Logger logger = LoggerUtil.getLogger();/*** "post" request to transfer "json" data** @param url* @param json* @param timeOutMS (Millisecond)* @return*/public static String doPostParmaMap(String url, Map<?, ?> json, Integer timeOutMS) {if (null == json) {return doPost(url, null, timeOutMS);}String formatJson = JsonUtils.toFormatJsonNoException(json);return doPost(url, formatJson, timeOutMS);}/*** "post" request to transfer "json" data** @param url* @param json* @param timeOutMS (Millisecond)* @return*/public static String doPost(String url, String json, Integer timeOutMS) {String result = "";// Create an "httpclient" objectCloseableHttpClient httpClient = null;// Create a "post" mode request objectHttpPost httpPost = null;try {// Create an "httpclient" objecthttpClient = HttpClients.createDefault();// Create a "post" mode request objecthttpPost = new HttpPost(url);logger.debug("afferent json param:" + json);// Set parameters to the request objectif (StringUtils.isNotBlank(json)) {StringEntity stringEntity = new StringEntity(json.toString(), ContentType.APPLICATION_JSON);stringEntity.setContentEncoding("utf-8");httpPost.setEntity(stringEntity);}httpPost.setProtocolVersion(HttpVersion.HTTP_1_1);if (null != timeOutMS) {// Set timeoutRequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(timeOutMS).build();httpPost.setConfig(requestConfig);}logger.info("call '" + url + "' start");// Perform the request operation and get the result (synchronous blocking)CloseableHttpResponse response = httpClient.execute(httpPost);logger.info("call succeeded,return msg:" + response.toString());// Get result entity// Determine whether the network connection status code is normal (0--200 are normal)switch (response.getStatusLine().getStatusCode()) {case HttpStatus.SC_OK:result = EntityUtils.toString(response.getEntity(), "utf-8");logger.info("call succeeded,return msg:" + result);break;case HttpStatus.SC_CREATED:result = EntityUtils.toString(response.getEntity(), "utf-8");logger.info("call succeeded,return msg:" + result);break;default:result = INTERFACE_CALL_ERROR + ":" + EntityUtils.toString(response.getEntity(), "utf-8");logger.warn("call failed,return msg:" + result);break;}} catch (UnsupportedCharsetException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":UnsupportedCharsetException");} catch (ClientProtocolException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ClientProtocolException");} catch (ParseException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ParseException");} catch (IOException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":IOException");} finally {// Close the connection and release the resourcehttpPost.releaseConnection();}return result;}/*** Get request to transfer data** @param url* @param map       Request incoming parameters ("key" is the parameter name, "value" is the parameter value) "map" can be empty* @param timeOutMS (Millisecond)* @return*/public static String doGet(String url, Map<String, String> map, Integer timeOutMS) {String result = "";if (StringUtils.isNotBlank(url)) {try {// Create an "httpclient" objectCloseableHttpClient httpClient = HttpClients.createDefault();// Create a "get" mode request objectHttpGet httpGet = null;// Determine whether to add parametersif (null != map && !map.isEmpty()) {// Since the parameters of the "GET" request are all assembled behind the "URL" address, we have to build a "URL" with parameters.URIBuilder uriBuilder = new URIBuilder(url);List<NameValuePair> list = new LinkedList<>();for (String key : map.keySet()) {BasicNameValuePair param = new BasicNameValuePair(key, map.get(key));list.add(param);}uriBuilder.setParameters(list);// Construct a "GET" request object from a "URI" object with parametershttpGet = new HttpGet(uriBuilder.build());} else {httpGet = new HttpGet(url);}// Add request header information// Browser representation// httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1;// en-US; rv:1.7.6)");// Type of transmission// httpGet.addHeader("Content-Type", "application/x-www-form-urlencoded");// Type of transmissionhttpGet.addHeader("Content-type", "application/json");if (null != timeOutMS) {// Set timeoutRequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(timeOutMS).build();httpGet.setConfig(requestConfig);}logger.info("call '" + url + "' start");// Get the response object by requesting the objectCloseableHttpResponse response = httpClient.execute(httpGet);//logger.info("call succeeded,return msg:" + response.toString());logger.info("call succeeded");// Get result entity// Determine whether the network connection status code is normal (0--200 are normal)switch (response.getStatusLine().getStatusCode()) {case HttpStatus.SC_OK:result = EntityUtils.toString(response.getEntity(), "utf-8");//logger.info("call succeeded,return msg:" + result);logger.info("call succeeded");break;case HttpStatus.SC_CREATED:result = EntityUtils.toString(response.getEntity(), "utf-8");logger.info("call succeeded,return msg:" + result);break;default:result = INTERFACE_CALL_ERROR + ":" + EntityUtils.toString(response.getEntity(), "utf-8");logger.warn("call failed,return msg:" + result);break;}// Release linkresponse.close();} catch (ClientProtocolException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ClientProtocolException");} catch (ParseException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ParseException");} catch (IOException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":IOException");} catch (URISyntaxException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":URISyntaxException");}}return result;}public static String getHtml(String urlStr) {// Define links to be accessedString url = urlStr;// Define a string to store web contentString result = "";// Define a buffered character input streamBufferedReader in = null;try {// Convert string to url objectURL realUrl = new URL(url);// Initialize a link to the "url" linkURLConnection connection = realUrl.openConnection();// Start the actual connectionconnection.connect();// Initialize the "BufferedReader" input stream to read the response of the "URL"in = new BufferedReader(new InputStreamReader(connection.getInputStream()));// Used to temporarily store data for each fetched rowString line;while ((line = in.readLine()) != null) {// Traverse each row that is fetched and store it in "result"result += line + "\n";}} catch (Exception e) {logger.error("send get request is abnormal!" + e);e.printStackTrace();} // Use "finally" to close the input streamfinally {try {if (in != null) {in.close();}} catch (Exception e2) {e2.printStackTrace();}}logger.debug("html info:" + result);return result;}/*** "post" request to transfer "json" data** @param url* @param timeOutMS (Millisecond)* @return*/public static String doDelete(String url, Integer timeOutMS) {String result = "";// Create an "httpclient" objectCloseableHttpClient httpClient = null;// Create a "post" mode request objectHttpDelete httpDelete = null;try {// Create an "httpclient" objecthttpClient = HttpClients.createDefault();// Create a "post" mode request objecthttpDelete = new HttpDelete(url);httpDelete.setProtocolVersion(HttpVersion.HTTP_1_1);if (null != timeOutMS) {// Set timeoutRequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(timeOutMS).build();httpDelete.setConfig(requestConfig);}logger.info("call '" + url + "' start");// Perform the request operation and get the result (synchronous blocking)CloseableHttpResponse response = httpClient.execute(httpDelete);logger.info("call succeeded,return msg:" + response.toString());// Get result entity// Determine whether the network connection status code is normal (0--200 are normal)switch (response.getStatusLine().getStatusCode()) {case HttpStatus.SC_OK:result = EntityUtils.toString(response.getEntity(), "utf-8");logger.info("call succeeded,return msg:" + result);break;case HttpStatus.SC_CREATED:result = EntityUtils.toString(response.getEntity(), "utf-8");logger.info("call succeeded,return msg:" + result);break;default:result = INTERFACE_CALL_ERROR + ":" + EntityUtils.toString(response.getEntity(), "utf-8");logger.warn("call failed,return msg:" + result);break;}} catch (UnsupportedCharsetException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":UnsupportedCharsetException");} catch (ClientProtocolException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ClientProtocolException");} catch (ParseException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":ParseException");} catch (IOException e) {logger.error(INTERFACE_CALL_ERROR, e);result = (INTERFACE_CALL_ERROR + ":IOException");} finally {// Close the connection and release the resourcehttpDelete.releaseConnection();}return result;}
}
JsonUtils.java
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;/*** Json utils*/
@SuppressWarnings("deprecation")
public class JsonUtils {private static final ObjectMapper objectMapper;private static Logger logger = LoggerUtil.getLogger();static {objectMapper = new ObjectMapper();// Remove the default timestamp formatobjectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);// Set to Shanghai time zone in ChinaobjectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);// Null value not serializedobjectMapper.setSerializationInclusion(Include.NON_NULL);// Compatible processing when attributes are not present during deserializationobjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);// Uniform format of dates when serializingobjectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));// It is forbidden to deserialize "Enum" with "int" on behalf of "Enum"objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);// objectMapper.configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY,// true);objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);// Single quote processingobjectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);// objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE);}public static <T> T toObjectNoException(String json, Class<T> clazz) {try {return objectMapper.readValue(json, clazz);} catch (JsonParseException e) {logger.error(e.getMessage(), e);} catch (JsonMappingException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);}return null;}public static <T> String toJsonNoException(T entity) {try {return objectMapper.writeValueAsString(entity);} catch (JsonGenerationException e) {logger.error(e.getMessage(), e);} catch (JsonMappingException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);}return null;}public static <T> String toFormatJsonNoException(T entity) {try {return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(entity);} catch (JsonGenerationException e) {logger.error(e.getMessage(), e);} catch (JsonMappingException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);}return null;}public static <T> T toCollectionNoException(String json, TypeReference<T> typeReference) {try {return objectMapper.readValue(json, typeReference);} catch (JsonParseException e) {logger.error(e.getMessage(), e);} catch (JsonMappingException e) {logger.error(e.getMessage(), e);} catch (IOException e) {logger.error(e.getMessage(), e);}return null;}/*** Object to "json" string** @param object* @return* @throws JsonProcessingException*/public static String toString(Object object) throws JsonProcessingException {return objectMapper.writeValueAsString(object);}/*** "json" string to object** @param jsonString* @param rspValueType* @return* @throws JsonParseException* @throws JsonMappingException* @throws IOException*/public static <T> T toObject(String jsonString, Class<T> rspValueType)throws JsonParseException, JsonMappingException, IOException {return objectMapper.readValue(jsonString, rspValueType);}public static JsonNode readJsonNode(String jsonStr, String fieldName) {if (StringUtils.isEmpty(jsonStr)) {return null;}try {JsonNode root = objectMapper.readTree(jsonStr);return root.get(fieldName);} catch (IOException e) {logger.error("parse json string error:" + jsonStr, e);return null;}}@SuppressWarnings("unchecked")public static <T> T readJson(JsonNode node, Class<?> parametrized, Class<?>... parameterClasses) throws Exception {JavaType javaType = objectMapper.getTypeFactory().constructParametricType(parametrized, parameterClasses);return (T) objectMapper.readValue(toString(node), javaType);}/*** When converting "JSON" when using "Jackson", the date format setting "Jackson" two methods set the date format of the output* <p>* 1. Ordinary way: The default is to convert to "timestamps" form, you can cancel "timestamps" by the following way.* objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS,* false); This will cause the time generation to use the so-called use a [ISO-8601]-compliant notation, which outputs a time similar to the following:* "1970-01-01T00:00:00.000+0000". Of course, you can also customize the output format:* objectMapper.getSerializationConfig().setDateFormat(myDateFormat);* The myDateFormat object is java.text.DateFormat, which uses the annotation method of checking java API 2.annotaion:* First define the format you need as follows* <p>* Then find the date get method on your POJO** @JsonSerialize(using = CustomDateSerializer.class) public Date getCreateAt()* { return createAt; }* <p>* "java" date object converted to "JSON" date formatted custom class via "Jackson" library* @date 2010-5-3*/public class CustomDateSerializer extends JsonSerializer<Date> {@Overridepublic void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)throws IOException, JsonProcessingException {SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");String formattedDate = formatter.format(value);jgen.writeString(formattedDate);}}
}

调用示例:

post请求

String doPost = HttpUtils.doPost("url", formatJson,  5 * 1000); //5秒
JSONObject obj = JSONObject.fromObject(doPost).getJSONObject("test");

get请求

Map<String, String> map = new HashMap<>();
map.put("parms", parms);
String doGet = HttpUtils.doGet("url", map, 10 * 1000); //10秒
String jsonResult = JSONObject.fromObject(doGet).getString("test");
JSONObject obj = JSONObject.fromObject(jsonResult);

以前工具仅供参考!! 

相关文章:

java实现Http请求方式的几种常见方式

背景 在实际开发过程中&#xff0c;我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范&#xff0c;所以大多数需要去调用对方提供的接口或第三方接口&#xff08;短信、天气等&#xff09;。若是普通java工程推荐使用OkHt…...

安卓开发,底部导航栏

1、创建导航栏图标 使用系统自带的矢量图库文件&#xff0c;鼠标右键点击res->New->Vector Asset 修改 Name , Clip art 和 Color 再创建一个 同样的方法再创建四个按钮 2、添加百分比布局依赖 app\build.gradle.kts 中添加百分比布局依赖&#xff0c;并点击Sync Now …...

Spring Boot中实现多租户架构

文章目录 Spring Boot中实现多租户架构多租户架构概述核心思想多租户的三种模式优势挑战租户识别机制1. 租户标识(Tenant Identifier)2. 常见的租户识别方式3. 实现租户识别的关键点4. 租户识别示例代码5. 租户识别机制的挑战数据库隔离的实现1. 数据库隔离的核心目标2. 数据…...

SpringBoot源码解析(十):应用上下文AnnotationConfigServletWebServerApplicationContext构造方法

SpringBoot源码系列文章 SpringBoot源码解析(一)&#xff1a;SpringApplication构造方法 SpringBoot源码解析(二)&#xff1a;引导上下文DefaultBootstrapContext SpringBoot源码解析(三)&#xff1a;启动开始阶段 SpringBoot源码解析(四)&#xff1a;解析应用参数args Sp…...

vue3+vite全局loading

vue3vite全局loading j-loading.vue组件 <template><transition enter-active-class"animate__animated animate__fadeIn"leave-active-class"animate__animated animate__fadeOut"><div class"root-box" v-if"show"…...

比亚迪发布智能化战略,天神之眼开创全民智驾

2月10日&#xff0c;比亚迪在深圳隆重召开智能化战略发布会&#xff0c;正式向全球发布了其最新的智驾技术——“天神之眼”。这一技术的发布&#xff0c;标志着比亚迪在智能驾驶领域迈出了坚实的一步&#xff0c;稳居行业第一梯队&#xff0c;真正实现了端到端的智能驾驶体验&…...

在 MySQL 中,通过存储过程结合条件判断来实现添加表字段时,如果字段已存在则不再重复添加

-- 创建存储过程 DELIMITER $$ CREATE PROCEDURE add_column(IN db_name VARCHAR(255),IN table_name VARCHAR(255),IN column_name VARCHAR(255),IN column_definition VARCHAR(255),IN column_comment VARCHAR(255) ) BEGINDECLARE column_exists INT;-- 检查字段是否存在SEL…...

UP-VLA:具身智体的统一理解与预测模型

25年1月来自清华大学和上海姚期智研究院的论文“UP-VLA: A Unified Understanding and Prediction Model for Embodied Agent”。 视觉-语言-动作 (VLA) 模型的最新进展&#xff0c;利用预训练的视觉语言模型 (VLM) 来提高泛化能力。VLM 通常经过视觉语言理解任务的预训练&…...

后端开发ThreadLocal简介

ThreadLocal是线程的局部变量&#xff0c;为每个线程单独提供一份存储空间&#xff0c;具有线程隔离的效果&#xff0c;只有线程内能获取到对应的值 客户端发起的每次请求都对应一个单独的线程 常用方法 public void set(T value) 设置当前线程局部变量值public T get() 返回…...

AI分支知识之机器学习,深度学习,强化学习的关系

机器学习&#xff0c;深度学习&#xff0c;强化学习的关系 这一篇文章我们来探讨下AI领域中机器学习&#xff08;ML&#xff09;、深度学习&#xff08;DL&#xff09;和强化学习&#xff08;RL&#xff09;的关系。 一、机器学习&#xff08;ML&#xff09;&#xff1a;从数…...

微信小程序案例2——天气微信小程序(学会绑定数据)

文章目录 一、项目步骤1 创建一个weather项目2 进入index.wxml、index.js、index.wxss文件,清空所有内容,进入App.json,修改导航栏标题为“中国天气网”。3进入index.wxml,进行当天天气情况的界面布局,包括温度、最低温、最高温、天气情况、城市、星期、风行情况,代码如下…...

CPLD实现SPI通信

在 CPLD 中编写 SPI 程序时,需根据具体需求(主/从设备、时钟极性、数据位宽等)设计逻辑。以下提供一个 SPI 主控制器的 Verilog 实现示例,支持 模式 0(CPOL=0, CPHA=0),适用于控制外设(如 ADC、DAC、存储器等)。 SPI 主控制器模块设计(Verilog) 模块功能 支持 8/16…...

FFmpeg + OpenGL ES 美颜相机教程大纲

做OpenGL和FFmpeg也有很长一段时间了&#xff0c;最近打算结合FFmpegOpenGL ES做一期视频教程&#xff0c;下面是完整视频教程大纲。最终的项目实战效果是实现一款美颜相机。教程分为理论讲解和实战开发两部分&#xff0c;适合有一定编程基础的开发者。课程计划是免费发布在B站…...

dynamic_cast和static_cast和const_cast

dynamic_cast 在 C 中的作用 dynamic_cast 是 C 运行时类型转换&#xff08;RTTI, Run-Time Type Identification&#xff09;的一部分&#xff0c;主要用于&#xff1a; 安全的多态类型转换检查类型的有效性向下转换&#xff08;Downcasting&#xff09;跨类层次的指针或引用…...

SQLMesh系列教程-2:SQLMesh入门项目实战

假设你已经了解SQLMesh是什么&#xff0c;以及其他应用场景。如果没有&#xff0c;我建议你先阅读《SQLMesh系列教程-1&#xff1a;数据工程师的高效利器-SQLMesh》。 在本文中&#xff0c;我们将完成一个小项目或教程&#xff0c;以帮助你开始使用SQLMesh。你可以选择一步一步…...

window 安装GitLab服务器笔记

视频&#xff1a; windows下内网本地部署gitlab 资源&#xff1a; Linux CeneOS7&#xff1a; CentOS7 镜像下载地址 VMware&#xff1a; 虚拟机17.6下载地址 安装vim编辑器 yum install vim -y系统环境升级&#xff08;我第一次没有使用。第二次成功使用了的&#xff09;…...

【逆向工程】破解unity的安卓apk包

先了解一下普通apk包的逆向方法&#xff08;无加密或加壳&#xff09; 开发环境&#xff1a; 操作系统&#xff1a;windows 解apk包 下载工具&#xff1a;apktool【Install Guide | Apktool】按照文档说的操作就行&#xff0c;先安装java运行时环境【我安装的是jre-8u441-wind…...

2021版小程序开发5——小程序项目开发实践(2)-完

2021版小程序开发5——小程序项目开发实践(2) 学习笔记 2025 使用uni-app开发一个电商项目继续&#xff1b; 过滤器的使用 filters: {toFixed(num){return Number(num).toFixed(2)} }<!-- 通过管道符 | 使用过滤器 --> <view> {{ item.price | toFixed }}</vi…...

Spring Boot牵手Redisson:分布式锁实战秘籍

一、引言 在当今的分布式系统架构中,随着业务规模的不断扩大和系统复杂度的日益增加,如何确保多个服务节点之间的数据一致性和操作的原子性成为了一个至关重要的问题。在单机环境下,我们可以轻松地使用线程锁或进程锁来控制对共享资源的访问,但在分布式系统中,由于各个服务…...

【HarmonyOS Next 自定义可拖拽image】

效果图&#xff1a; 代码&#xff1a; import display from "ohos.display" import { AppUtil } from "pura/harmony-utils"/*** 自定义可拖拽图标组件*/ Component export default struct DraggableImage {imageResource?: ResourceimageHeight: numbe…...

基于扑克牌分发效果制作时的问题总结

其基本效果如图 1. 在overlay模式下直接使用position来移动 实现代码 public class Card : MonoBehaviour {public RectTransform target;public Button cardButton;private bool isPack false;public List<RectTransform> cards new List<RectTransform>(…...

为多个GitHub账户配置SSH密钥

背景 当需要同时使用多个GitHub账户&#xff08;例如工作和个人账户&#xff09;时&#xff0c;默认的SSH配置可能导致冲突。本文介绍如何通过生成不同的SSH密钥对并配置SSH客户端来管理多个账户。 操作步骤 生成SSH密钥对 为每个GitHub账户生成独立的密钥对&#xff0c;并指…...

三步本地部署deepseekr1,支持macOs,ubuntu,Windows

一、ollama安装: ollama官网:Ollama Ollama 是一款支持在 Windows、macOS 和 Linux 上本地运行大型语言模型的工具。以下是针对不同操作系统的安装指南: 1、Windows 系统 下载安装包:访问 Ollama 官方下载页面,选择适用于 Windows 的安装包进行下载。 运行安装程序:下…...

STM32 HAL库 CANbus通讯(C语言)

#include "main.h" #include "stm32f1xx_hal.h"CAN_HandleTypeDef hcan; CAN_TxHeaderTypeDef TxHeader; CAN_RxHeaderTypeDef RxHeader; uint8_t TxData[8]; uint8_t RxData[8]; uint32_t TxMailbox;void CAN_Init(void) {// 使能CAN时钟__HAL_RCC_CAN1_C…...

Cotex-M系列介绍

一、芯片设计公司——ARM ARM公司&#xff1a;只做内核设计和IP授权&#xff0c;不参与芯片设计 二、Cortex内核分类及特征...

测试自动化落地方向

一、视觉回归自动化测试&#xff08;低成本高回报&#xff09; 痛点&#xff1a; UI 频繁迭代导致视觉问题难覆盖 方案&#xff1a; 引入Applitools或SikuliX做视觉比对&#xff08;无需维护元素定位&#xff09; 关键路径截图比对&#xff0c;自动检测 UI 错位/样式问题 亮点…...

如何通过优化网站结构提高SEO效果?

很多人以为&#xff0c;SEO就是写写关键词&#xff0c;发点外链&#xff0c;但其实&#xff0c;网站结构才是排名的地基&#xff01;你可以把网站想象成一栋房子&#xff0c;框架没搭好&#xff0c;装饰再漂亮也没用&#xff0c;迟早会塌。同样的道理&#xff0c;如果网站结构混…...

迅雷下载的原理和使用协议的分析

迅雷作为一款广泛使用的下载工具&#xff0c;其核心原理是通过整合多种下载协议和资源分发技术来提升下载速度。以下是对其原理及协议的详细分析&#xff1a; 一、迅雷下载的核心原理 多协议混合下载&#xff08;P2SP&#xff09; P2SP&#xff08;Peer-to-Server-Peer&#xf…...

RPA与深度学习结合

什么是RPA RPA即机器人流程自动化&#xff08;Robotic Process Automation&#xff09;&#xff0c;它是一种利用软件机器人模拟人类在计算机上的操作&#xff0c;按照预设的规则自动执行一系列重复性、规律性任务的技术。这些任务可以包括数据录入、文件处理、报表生成、系统…...

Linux内核模块参数与性能优化:__read_mostly属性的深度剖析

在Linux内核开发中,模块参数和性能优化是两个至关重要的主题。模块参数允许开发者和用户在加载内核模块时动态配置模块的行为,而性能优化则是确保内核高效运行的关键。本文将深入探讨Linux内核中的模块参数机制以及__read_mostly属性的使用,通过实际代码示例和详细解释,帮助…...

Elasticsearch:如何使用 Elastic 检测恶意浏览器扩展

作者&#xff1a;来着 Elastic Aaron Jewitt 当你的 CISO 询问你的任何工作站上是否安装过特定的浏览器扩展时&#xff0c;你多快能得到正确答案&#xff1f;恶意浏览器扩展是一个重大威胁&#xff0c;许多组织无法管理或检测。这篇博文探讨了 Elastic Infosec 团队如何使用 os…...

基于Java的远程视频会议系统(源码+系统+论文)

第一章 概述 1.1 本课题的研究背景 随着人们对视频和音频信息的需求愈来愈强烈&#xff0c;追求远距离的视音频的同步交互成为新的时尚。近些年来&#xff0c;依托计算机技术、通信技术和网络条件的发展&#xff0c;集音频、视频、图像、文字、数据为一体的多媒体信息&#xff…...

SAP-ABAP:FOR ALL ENTRIES IN用法详解带实例代码

在 SAP ABAP 中&#xff0c;FOR ALL ENTRIES IN 是 SELECT 语句中一个非常常用的功能&#xff0c;用于根据内表中的数据查询数据库表。它的主要作用是将内表中的数据作为查询条件&#xff0c;从数据库表中筛选出符合条件的数据。 1. 基本语法 SELECT <fields>FROM <d…...

构建jdk17包含maven的基础镜像

1、先拉取jdk17基础镜像 docker pull openjdk:17-jdk-alpine 2、使用jdk17基础镜像创建容器 docker run -it openjdk:17-jdk-alpine sh 或 docker run -it --name jdk17 openjdk:17-jdk-alpine sh 3、修改镜像源地址 cat /etc/apk/repositories https://mirrors.aliyun.com…...

【Android】版本和API对应关系表

目录 版本和API对应关系表 不积跬步&#xff0c;无以至千里&#xff1b;不积小流&#xff0c;无以成江海。要沉下心来&#xff0c;诗和远方的路费真的很贵&#xff01; 版本和API对应关系表 版本名版本号名称APIAndroid 1616.0W36Android 1515.0V35Android 1414.0U34Android 1…...

Spring Boot 整合 JPA 实现数据持久化

目录 前言 一、JPA 核心概念与实体映射 1. 什么是 JPA&#xff1f; 2. JPA 的主要组件 3. 实体映射 4. 常见的字段映射策略 二、Repository 接口与自定义查询 1. 什么是 Repository 接口&#xff1f; 2. 动态查询方法 3. 自定义查询 4. 分页与排序 三、实战案例&…...

KUKA 机器人仿真——Simpro4.1和OfficeLite8.6.2 连接实现虚拟示教器

一、准备软件 1、Simpro4.1&#xff0c;是一机一密钥&#xff0c;不好破解&#xff0c;我在某宝买的&#xff0c;省事了。 2、OfficeLite8.6.2&#xff0c;看我的博文的第三步虚拟机内安装OfficeLite8.6.2 KUKA示教器仿真软件OfficeLite8.6.2&#xff0c;EthernetKRL3.1.3通信…...

IntelliJ IDEA使用经验(十三):使用Git克隆github的开源项目

文章目录 问题背景办法1、设置git代理&#xff1b;2、再次克隆项目&#xff1b;3、再次按常规方式进行git克隆即可。 问题背景 由于github在国外&#xff0c;很多时候我们在使用idea克隆开源项目的时候&#xff0c;没办法检出&#xff0c;提示 连接重置。 办法 1、设置git代…...

互联网大厂中面试的高频计算机网络问题及详解

前言 哈喽各位小伙伴们,本期小梁给大家带来了互联网大厂中计算机网络部分的高频面试题,本文会以通俗易懂的语言以及图解形式描述,希望能给大家的面试带来一点帮助,祝大家offer拿到手软!!! 话不多说,我们立刻进入本期正题! 一、计算机网络基础部分 1 先来说说计算机网…...

综合实验练习实验报告

一、需求分析 1.防火墙上配置DHCP服务&#xff0c;完成接口配置 2.用户建立以及认证策略建立 3.安全策略建立 二、详细配置 DHCP配置 [FW1]dhcp enable [FW1]int g1/0/1.1 [FW1-GigabitEthernet1/0/1.1]dhcp select interface [FW1]int g1/0/1.2 [FW1-GigabitEthernet…...

Ubuntu22.04 配置deepseek知识库

文章目录 安装 docker配置 dify配置 ollama创建大模型 安装 docker 更新系统&#xff1a;sudo apt update sudo apt upgrade -y安装必要的依赖&#xff1a;sudo apt install apt-transport-https ca-certificates curl software-properties-common -y添加 Docker 的官方 GPG 密…...

如何在WPS和Word/Excel中直接使用DeepSeek功能

以下是将DeepSeek功能集成到WPS中的详细步骤&#xff0c;无需本地部署模型&#xff0c;直接通过官网连接使用&#xff1a;1. 下载并安装OfficeAI插件 &#xff08;1&#xff09;访问OfficeAI插件下载地址&#xff1a;OfficeAI助手 - 免费办公智能AI助手, AI写作&#xff0c;下载…...

Mp4视频播放机无法播放视频-批量修改视频分辨率(帧宽、帧高)

背景 家人有一台夏新多功能 视频播放器(夏新多功能 视频播放器),用来播放广场舞。下载了一些广场舞视频, 只有部分视频可以播放,其他视频均无法播放,判断应该不是帧速率和数据速率的限制, 分析可能是播放器不支持帧高度大于720的视频。由于视频文件较多,需要借助视频编…...

jvm 线程监控调试

文章目录 前言一、使用JDK工具转储线程文件(如jstack)1. 找到Java进程的PID:2. 使用jstack生成线程转储文件:3.验证生成的线程转储文件:二、分析文件1.使用在线工具进行分析上传thread-dump文件,等待解析完成2.查看分析结果总结前言 提示:使用jdk自带工具转储线程监控文…...

超越 DeepSeek V3 -->【Qwen2.5-Max】

&#x1f525; 先说明&#xff0c;不是广子&#xff0c;不是广子&#xff01;&#xff01;&#xff01;单纯分享这个工具给大家&#xff0c;毕竟最近使用 DeepSeek 太容易崩了&#xff0c;每天深度思考一次之后就开始转圈圈用不了&#xff0c;然后就找到了这个工具使用 一、前言…...

301.华为交换机堆叠技术基础

华为交换机堆叠技术基础 一、概念及原理部分1.堆叠简介1.1 什么是堆叠1.2 可靠性网络架构1.3 华为堆叠设备1.4 其他厂商的堆叠2.堆叠的示意图3.堆叠的应用3.1 中小企业3.2 园区网4.堆叠的原理4.1基本的概念4.2 堆叠建立4.3 角色选举4.4 版本同步4.5 配置同步4.6 堆叠系统的登录…...

【开源AI】AI一页一页读PDF

【开源AI】AI一页一页读PDF 可以在这里看 : 让AI 处理 PDF 文件,提取其中的知识点,并生成总结。 只是无法修改,后续若有更新在csdn这里。 【OpenAI】 API 更新: JSON 结构化输出约束机制( JSON Schema) 的一次实战。知识库的JSON Schema形式 每一页都要总结,总结的知识…...

Spring AI 介绍

文章来源&#xff1a;AI 概念 (AI Concepts) _ Spring AI1.0.0-SNAPSHOT中文文档(官方文档中文翻译)|Spring 教程 —— CADN开发者文档中心 本节介绍 Spring AI 使用的核心概念。我们建议仔细阅读它&#xff0c;以了解 Spring AI 是如何实现的。 模型 AI 模型是旨在处理和生成…...

React - 事件绑定this

在 React 中&#xff0c;this 的绑定是一个常见问题&#xff0c;尤其在类组件中使用事件处理函数时。JavaScript 中的 bind 函数用于设置函数调用时 this 的值。 bind 函数的作用 bind() 方法创建一个新的函数&#xff0c;当被调用时&#xff0c;其 this 关键字被设置为提供的…...

【3.Git与Github的历史和区别】

目录 Git的历史和Github的区别本质和功能 Git的历史和Github的区别 Git是由Linux内核的创造者Linus Torvalds于2005年创建的。当时&#xff0c;Linux内核开源项目使用BitKeeper作为版本控制系统&#xff0c;但2005年BitKeeper的商业公司终止了与Linux社区的合作&#xff0c;收…...