长用工具类 介绍 httpclient

httpclient

官网

依赖

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议
的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
//demo
public static void main(String[] args) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault(); // 创建httpclient实例
        HttpGet httpget = new HttpGet("https://www.baidu.com/"); // 创建httpget实例
         
        CloseableHttpResponse response = httpclient.execute(httpget); // 执行get请求
        HttpEntity entity=response.getEntity(); // 获取返回实体
        System.out.println("网页内容:"+EntityUtils.toString(entity, "utf-8")); // 指定编码打
印网页内容
        response.close(); // 关闭流和释放系统资源
    }
 /**
     * 连接超时和读取超时
     * HttpClient连接时间
 
     所谓连接的时候 是HttpClient发送请求的地方开始到连接上目标url主机地址的时间,理论上是距离越
短越快,
 
     线路越通畅越快,但是由于路由复杂交错,往往连接上的时间都不固定,运气不好连不上,HttpClient
的默认连接时间,据我测试,
 
     默认是1分钟,假如超过1分钟 过一会继续尝试连接,这样会有一个问题 假如遇到一个url老是连不上,
会影响其他线程的线程进去,说难听点,
 
     就是蹲着茅坑不拉屎。所以我们有必要进行特殊设置,比如设置10秒钟 假如10秒钟没有连接上 我们就报
错,这样我们就可以进行业务上的处理,
 
     比如我们业务上控制 过会再连接试试看。并且这个特殊url写到log4j日志里去。方便管理员查看。
     */
    /**
     * HttpClient读取时间
 
     所谓读取的时间 是HttpClient已经连接到了目标服务器,然后进行内容数据的获取,一般情况 读取数
据都是很快速的,
 
     但是假如读取的数据量大,或者是目标服务器本身的问题(比如读取数据库速度慢,并发量大等等..)也
会影响读取时间。
 
     同上,我们还是需要来特殊设置下,比如设置10秒钟 假如10秒钟还没读取完,就报错,同上,我们可以
业务上处理。
 
 
     */
    @Test
    public void timeout() throws Exception{
        CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet=new HttpGet("http://central.maven.org/maven2/"); // 创建httpget实例
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(10000) //连接十秒钟
                .setSocketTimeout(100)// 读取超时 1000 ms可以读完
                .build();
        httpGet.setConfig(config);
        CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求
        HttpEntity entity=response.getEntity(); // 获取返回实体
        System.out.println("网页内容:"+EntityUtils.toString(entity, "utf-8")); // 获取网页内容
        response.close(); // response关闭
        httpClient.close(); // httpClient关闭
//     结果   java.net.SocketTimeoutException: Read timed out
    }

 String.format(format,args)

   /**
     %s	字符串类型	“喜欢请收藏”
     %c	字符类型	'm'
     %b	布尔类型	true
     %d	整数类型(十进制)	88
     %x	整数类型(十六进制)	FF
     %o	整数类型(八进制)	77
     %f	浮点类型	8.888
     %a	十六进制浮点类型	FF.35AE
     %e	指数类型	9.38e+5
     %g	通用浮点类型(f和e类型中较短的)	不举例(基本用不到)
     %h	散列码	不举例(基本用不到)
     %%	百分比类型	%(%特殊字符%%才能显示%)
     %n	换行符	不举例(基本用不到)
     %tx	日期与时间类型(x代表不同的日期与时间转换符)	不举例(基本用不到)
     */
    @Test
    public void t1(){
        String str=null;
        str=String.format("Hi,%s", "xx"); //请示%s 就相当于字符串的占位符
        System.out.println(str);//Hi,xx
        str=String.format("Hi,%s:%s.%s", "张三","李四","王张");//Hi,张三:李四.王张
        System.out.println(str);
        System.out.printf("字母a的大写是:%c %n", 'A');
        
    }
}

拷贝对象的属性 

//import org.springframework.beans.BeanUtils;

		People people=new People();
//		people.setAge(12);
		people.setName("cc");
//		people.setAddr("ss");
		Person person=new Person();
		
		BeanUtils.copyProperties(people,person);
		System.out.println(person);

拷贝属性的值,不管(source)people的属性和(dest)people 相比多还是少,只要属性一直就可以赋值

拷贝文件

	<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.5</version>
		</dependency>

apache 工具
FileUtils.copyToFile(stream, new File("b.png"));//流拷贝   commons-io里
FileUtils.copyFile(new File("book.txt"),new File("c.txt")); //一个文件拷贝到另一个文件

spring内置
FileCopyUtils.copy(new File("book.txt"),new File("b.txt"));//一个文件拷贝到另一个文件

判断集合是否为空apache 和spring

  public static boolean isEmpty(@Nullable Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }

    public static boolean isEmpty(@Nullable Map<?, ?> map) {
        return map == null || map.isEmpty();
    }

	if(!CollectionUtils.isEmpty(map)){
			System.out.println("tda");
		}

加载配置文件 

Properties properties = PropertiesLoaderUtils.loadProperties(new 
ClassPathResource("application.properties"));
		String property = properties.getProperty("server.port");
		System.out.println(property);

@RequestBody的使用

@RequestBody主要用来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);GET方式无请求
体,、所以使用@RequestBody接收数据时,前端不能使用GET方式提交数据,而是用POST方式进行提交。在后端
的同一个接收方法里,@RequestBody与@RequestParam()可以同时使用,@RequestBody最多只能有一个,而
@RequestParam()可以有多个。

   @RequestMapping("/ct")
    public void Ct(@RequestBody @Valid People p, BindingResult result){
       if(result.hasErrors()){
           System.out.println(result.getFieldError().getDefaultMessage());
       }
       System.out.println(p.getAge()+""+p.getName());
    }
}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class People {
    @NotEmpty(message = "姓名")
    private String name;
    private String addr;
    private Integer age;
    
}

-----测试结果-------
12--xc
-----------------------------------------------------------------------------
   @RequestMapping("/ct")
    public void Ct(@RequestBody @Valid String s, BindingResult result){
      
        System.out.println(s);  //---string接收前端全部的字符串 传什么就是什么
    }
}

guava

<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>16.0</version>
        </dependency>

拆分器 spliter

 String s="a|b|c | || ";
        List<String> strings = Splitter.on("|").omitEmptyStrings().trimResults().splitToList(s);
        System.out.println(strings);//[a, b, c] omitEmptyStrings 忽略空元素 trimResults()//
忽略空格
String s = "a=ss|b=ss|c=b | || ";
Map<String, String> split = 
Splitter.on("|").omitEmptyStrings().trimResults().withKeyValueSeparator("=").split(s);
System.out.println(split);//{a=ss, b=ss, c=b}

joiner

 List<String> strings = Arrays.asList("cc", "dd", "ee","",null);
        String collect = strings.stream().filter((x) -> x != null && 
!x.equals("")).collect(Collectors.joining("#"));//cc#dd#ee


 String join = Joiner.on("#").skipNulls().join(strings);
        //为空值设置默认值
        String join1 = Joiner.on(",").useForNull("xx").join(1, 3, 5,null);
        System.out.println(join1);//1,3,5,xx

集合

         List<String> list = Lists.newArrayList("aa", "cc", "dd");//list
         HashSet<Object> objects = Sets.newHashSet(1,2,3);//set
         HashMap<Object, Object> objectObjectHashMap = Maps.newHashMap();
//多map
 Multimap<String, Object> multimap1= HashMultimap.create();
        multimap1.put("1","cc");
        multimap1.put("1","dd");
        System.out.println(multimap1.get("1"));//[cc, dd]
//bimap
 HashBiMap<String, String> biMap = HashBiMap.create();
        biMap.put("cc","dd");
        BiMap<String, String> inverse = biMap.inverse();//bimap{key 和value的反转}
//table
  Table<String, String, String> table = HashBasedTable.create();
        table.put("a","b","c");
        table.put("a","xx","dd");//{a={xx=dd, b=c}}
        System.out.println(table.row("a").get("xx"));//dd
//    ====      Map<String,Map<String,String>> map
    System.out.println(table.column("xx"));//dd
    System.out.println(table.column("xx"));//{a=dd}

//不可变的集合 -只能读-不能添加元素
  //不可变list
 ImmutableList<Integer> of = ImmutableList.of(1, 5, 4);
 ImmutableList<Integer> list = ImmutableList.copyOf(lists);//[1, 5, 4]   

//   不可变map
        ImmutableMap<String, String> immutableMap = ImmutableMap.of("1", "od", "cc", "d", 
"c", "s");//不能有相同的map


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值