package com.example.li.lichao.httputil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpUtil {
private static String date;
public String getdate(int page){
String url = "http://www.xieast.com/api/news/news.php?type=top&page=";
url+=page;
try {
URL url1 = new URL(url);
try {
HttpURLConnection urlConnection = (HttpURLConnection) url1.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(5000);
urlConnection.setConnectTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode == 200){
date = String2date(urlConnection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return date;
}
private String String2date(InputStream inputStream) {
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
try {
for (String msg = bufferedReader.readLine();msg != null;msg=bufferedReader.readLine()){
stringBuilder.append(msg);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
抽取URLConnection
最新推荐文章于 2022-03-25 11:16:50 发布