- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class HttpUtils {
- public static String readURL(String path){
- try {
- URL url = new URL(path);
- HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
- openConnection.setConnectTimeout(1000);
- openConnection.setReadTimeout(1000);
- openConnection.connect();
- //防止出现403
get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
- int responseCode = openConnection.getResponseCode();
- if(200==responseCode){
- InputStream inputStream = openConnection.getInputStream();
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- byte [] by = new byte[1024];
- int len = -1;
- while((len = inputStream.read(by))!=-1){
- bos.write(by, 0, len);
- }
- return bos.toString("utf-8");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- }
请求数据
最新推荐文章于 2023-08-17 22:43:46 发布