平时可能有些需要要获取别的网站的一些数据。。。
写了个简单的例子。。。
抓取百度首页的数据。。。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetRemoteDataTest {
public static void main(String[] args) {
System.out.println(sendPost("http://www.baidu.com"));
}
public static String sendPost(String url) {
String result = "";
try {
URL httpurl = new URL(url);
HttpURLConnection httpConn = (HttpURLConnection) httpurl
.openConnection();
httpConn.setDoInput(true); // 允许输入流,默认是true,而doOutput - 允许输出流,默认是false
BufferedReader in = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("没有结果!" + e);
}
return result;
}
}
测试成功。。。
以下是转载一些相关文章。。。
URL myUrl = new URL(searchURL);
URLConnection myConn = (HttpURLConnection)myUrl.openConnection();
myConn.setRequestProperty("User-agent","Mozilla/4.0");
BufferedReader br = new BufferedReader(new InputStreamReader(myConn.getInputStream()));
那台Server上要这么做, 可能是要阻止一些网络机器人的访问(不过感觉不是很有用,用上面的方法就能破了)。
其实实现感觉也很简单, 加上一个Filter,判断如果request.getHeader("User-agent")为空的话,然后再response一个403 status就行。