相应内容格式 gzip
  TEZNKK3IfmPf 2023年11月15日 73 0
package com.bonc.mine.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.zip.GZIPInputStream;

/**
* Created on 2022/3/16.
*
* @author lichuanming
*
* 发送 get请求,针对gizp
*/
public class SendGetUntil {
public static String sendGet(String url) {
StringBuffer stringBuffer = new StringBuffer();
try {
URL realUrl = new URL(url);

HttpURLConnection httpURLConnection = (HttpURLConnection) realUrl.openConnection();
//在这里设置一些属性,详细见UrlConnection文档,HttpURLConnection是UrlConnection的子类
//设置连接超时为5秒
httpURLConnection.setConnectTimeout(5000);
//设定请求方式(默认为get)
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("accept", "*/*");
httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
httpURLConnection.setRequestProperty("contentType", "UTF-8");
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
//建立到远程对象的实际连接
httpURLConnection.connect();
GZIPInputStream gZIPInputStream = null;
String encoding = httpURLConnection.getContentEncoding();
if(encoding.equals("gzip")){
gZIPInputStream = new GZIPInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(gZIPInputStream));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//转化为UTF-8的编码格式
line = new String(line.getBytes("UTF-8"));
stringBuffer.append(line);
}
bufferedReader.close();
}else{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
//转化为UTF-8的编码格式
line = new String(line.getBytes("UTF-8"));
stringBuffer.append(line);
}
bufferedReader.close();
}
//返回打开连接读取的输入流,输入流转化为StringBuffer类型,这一套流程要记住,常用


httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}

不会,我可以学;落后,我可以追赶;跌倒,我可以站起来!




【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月15日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   20天前   46   0   0 java
  TEZNKK3IfmPf   2024年05月31日   54   0   0 java
TEZNKK3IfmPf