简简单单的这样:
<a href='http://www.google.com/search?q=java+book'>google search</a>
都可以阿!
<a href='http://www.google.com/search?q=java+book'>google search</a>
都可以阿!
解决方案 »
- java主线程唤醒子线程的疑问
- 求一个正则表达式,谢谢
- 怎样在jtable中删除一列??高手哦来
- 一个递归方法,想不出来,帮忙想想
- JDom操作xml的问题,请搞手帮忙啊!
- 请高手总结:有哪些知名的应用程序(EXE)是用Java开发的?谢谢!
- 问下如果只装JDK能作GUI开发波?
- <<左移位到底是带符号位的还是不带符号位的?java书里没有明确说明。
- 如何在一个jtable的cell中用一个JcomboBox显示一个Vector!
- Java 8 新特性 泛型,语法以及相关
- 收邮件时的中文转换问题
- 请问哪里有org.apache.lucene.analysis.cn.ChineseAnalyzer?
由于其中所有代码太多,这是其中我认为是最关键的一个部分:
public void connect() {
try {
URL url=new URL("http://www.google.com/search?q=java+book");
InputStream in = url.openStream();
BufferedInputStream buff = new BufferedInputStream(in);
Reader r = new InputStreamReader(buff);
int c = 0;
while ( (c = r.read()) != -1){
System.out.print((char)c);
}
} catch (MalformedURLException mfe) {
System.err.println(url + " is not a parsable URL");
} catch (IOException ioe) {
System.err.println(ioe);
}
}
我并不是要做一个简单的链接
import java.net.*;
import java.io.*;
import java.util.Properties;
import java.util.Enumeration;public class Http {
protected Socket client;
protected BufferedOutputStream sender;
protected BufferedInputStream receiver;
protected ByteArrayInputStream byteStream;
protected URL target;
private int responseCode=-1;
private String responseMessage="";
private String serverVersion="";
private Properties header = new Properties(); public Http() { } public Http(String url) {
GET(url) ;
} /* GET方法根据URL,会请求文件、数据库查询结果、程序运行结果等多种内容 */
public void GET(String url){
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort() );
String cmd = "GET " + getURLFormat(target) + " HTTP/1.0\r\n" + getBaseHeads() + "\r\n";
sendMessage(cmd);
receiveMessage();
}
catch(ProtocolException p){
p.printStackTrace();
return;
}
catch(UnknownHostException e){
e.printStackTrace();
return;
}
catch(IOException i){
i.printStackTrace();
return;
}
} /*
* HEAD方法只请求URL的元信息,不包括URL本身。若怀疑本机和服务器上的
* 文件相同,用这个方法检查最快捷有效。
*/
public void HEAD(String url){
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort());
String cmd = "HEAD " + getURLFormat(target) + " HTTP/1.0\r\n" + getBaseHeads() + "\r\n";
sendMessage(cmd);
receiveMessage();
}
catch(ProtocolException p){
p.printStackTrace();
return;
}
catch(UnknownHostException e){
e.printStackTrace();
return;
}
catch(IOException i){
i.printStackTrace();
return;
}
} /*
* POST方法是向服务器传送数据,以便服务器做出相应的处理。例如网页上常用的
* 提交表格。
*/
public void POST(String url,String content) {
try{
checkHTTP(url);
openServer(target.getHost(),target.getPort() );
String cmd = "POST " + getURLFormat(target) + " HTTP/1.0\r\n" + getBaseHeads();
cmd += "Content-type: application/x-www-form-urlencoded\r\n";
cmd += "Content-length: " + content.length() + "\r\n\r\n";
cmd += content + "\r\n";
sendMessage(cmd);
receiveMessage();
}
catch(ProtocolException p){
p.printStackTrace();
return;
}
catch(UnknownHostException e){
e.printStackTrace();
return;
}
catch(IOException i){
i.printStackTrace();
return;
} } protected void checkHTTP(String url) throws ProtocolException {
try{
URL target = new URL(url);
if(target == null || !target.getProtocol().toUpperCase().equals("HTTP")){
throw new ProtocolException("这不是HTTP协议");
}
this.target = target;
}
catch(MalformedURLException m) {
throw new ProtocolException("协议格式错误");
}
} /*
* 与Web服务器连接。若找不到Web服务器,InetAddress会引发UnknownHostException
* 异常。若Socket连接失败,会引发IOException异常。
*/
protected void openServer(String host,int port) throws UnknownHostException,IOException {
header.clear();
responseMessage="";
responseCode=-1; if(client!=null){
closeServer();
}
if(byteStream != null){
byteStream.close();
byteStream=null;
} InetAddress address = InetAddress.getByName(host);
client = new Socket(address,port==-1?80:port);
client.setSoTimeout(5000);
sender = new BufferedOutputStream(client.getOutputStream());
receiver = new BufferedInputStream(client.getInputStream());
} /* 关闭与Web服务器的连接 */
protected void closeServer() throws IOException {
if(client==null){
return;
}
try{
client.close();
sender.close();
receiver.close();
}
catch(IOException i){
throw i;
} client=null;
sender=null;
receiver=null;
} protected String getURLFormat(URL target) {
String spec = "http://" + target.getHost();
if(target.getPort()!=-1){
spec+=":"+target.getPort();
} return spec+=target.getFile();
} /* 向Web服务器传送数据 */
protected void sendMessage(String data) throws IOException{
sender.write(data.getBytes(),0,data.length());
sender.flush();
} /* 接收来自Web服务器的数据 */
protected void receiveMessage() throws IOException{
byte data[] = new byte[1024];
int count=0;
int word=-1;
// 解析第一行
while( (word=receiver.read())!=-1 ) {
if(word=='\r'||word=='\n') {
word=receiver.read();
if(word=='\n') word=receiver.read();
break;
}
if(count == data.length) data = addCapacity(data);
data[count++]=(byte)word;
}
String message = new String(data,0,count);
int = message.indexOf(32);
serverVersion = message.substring(0,);
while( <message.length() && message.charAt(+1)==32 ) ++;
responseCode = Integer.parseInt(message.substring(+1,+=4));
responseMessage = message.substring(,message.length()).trim(); // 应答状态码和处理请读者添加
switch(responseCode) {
case 400:
throw new IOException("错误请求");
case 404:
throw new FileNotFoundException( getURLFormat(target) );
case 503:
throw new IOException("服务器不可用" );
}
if(word==-1) throw new ProtocolException("信息接收异常终止");
int symbol=-1;
count=0;
// 解析元信息
while( word!='\r' && word!='\n' && word>-1) {
if(word=='\t') word=32;
if(count==data.length) data = addCapacity(data);
data[count++] = (byte)word;
parseLine: {
while( (symbol=receiver.read()) >-1 ) {
switch(symbol) {
case '\t':
symbol=32; break;
case '\r':
case '\n':
word = receiver.read();
if( symbol=='\r' && word=='\n') {
word=receiver.read();
if(word=='\r') word=receiver.read();
}
if( word=='\r' || word=='\n' || word>32) break parseLine;
symbol=32; break;
}
if(count==data.length) data = addCapacity(data);
data[count++] = (byte)symbol;
}
word=-1;
}
message = new String(data,0,count);
= message.indexOf(':');
String key = null;
if(>0) key = message.substring(0,);
++;
while( <message.length() && message.charAt()<=32 ) ++;
String value = message.substring(,message.length() );
header.put(key,value);
count=0;
}
// 获得正文数据
while( (word=receiver.read())!=-1) {
if(count == data.length) data = addCapacity(data);
data[count++] = (byte)word;
}
if(count>0) byteStream = new ByteArrayInputStream(data,0,count);
data=null;
closeServer();
} public String getResponseMessage() {
return responseMessage;
} public int getResponseCode() {
return responseCode;
} public String getServerVersion() {
return serverVersion;
} public InputStream getInputStream() {
return byteStream;
} public synchronized String getHeaderKey(int i) {
if(i>=header.size()){
return null;
}
Enumeration enum = header.propertyNames();
String key = null;
for(int j=0; j<=i; j++){
key = (String)enum.nextElement();
}
return key;
} public synchronized String getHeaderValue(int i) {
if(i>=header.size()) return null;
return header.getProperty(getHeaderKey(i));
} public synchronized String getHeaderValue(String key) {
return header.getProperty(key);
} protected String getBaseHeads() {
String inf = "User-Agent: IcewolfHttp/1.0\r\nAccept: www/source; text/html; image/gif; */*\r\n";
return inf;
} private byte[] addCapacity(byte rece[]){
byte temp[] = new byte[rece.length+1024];
System.arraycopy(rece,0,temp,0,rece.length);
return temp;
} public static void main(String [] args){
Http p = new Http();
p.GET("http://www.google.com/search?q=java+book");
byte[] bGets = new byte[1024];
ByteArrayInputStream pS = (ByteArrayInputStream)p.getInputStream();
int offset = 0;
while((offset=pS.read(bGets,0,1024)) != -1){
System.out.print(new String(bGets,0,offset));
}
}
}
URL url=new URL("http://www.google.com/");能行
URL url=new URL("http://www.google.com/search?q=java+book");不行原因:google的search程序(一个cgi)在获得请求后,他会去读http请求头(他的程序要用到里面的一些数据),用你的方式请求的话,是一个最简单的请求头,里面不包含他要用到的数据。所以不行。
403是拒绝请求的意思。解决方法:你如果要用java程序的方式来请求,就只有自己写http请求了,你可以通过java的Socket类来做这件事情。先建立一个host = "www.google.com" port=80的Socket连接。然后构造http请求,最后接收。
由于我是教育网,我在其中加入设置代理的代码,
public static void main(String[] args) {
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "202.102.52.93");
System.getProperties().put("proxyPort", "3128"); Http p = new Http();
p.GET("http://www.google.com/search?q=java+book");
byte[] bGets = new byte[1024];
ByteArrayInputStream pS = (ByteArrayInputStream) p.getInputStream();
int offset = 0;
while ( (offset = pS.read(bGets, 0, 1024)) != -1) {
System.out.print(new String(bGets, 0, offset));
}
}
}
我的代理是可以用的,却出现了如下错误:
java.net.ConnectException: Connection timed out: connect at java.net.PlainSocketImpl.socketConnect(Native Method) at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:305) at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:171) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:158) at java.net.Socket.connect(Socket.java:426) at java.net.Socket.connect(Socket.java:376) at java.net.Socket.<init>(Socket.java:291) at java.net.Socket.<init>(Socket.java:147) at Http.openServer(Http.java:138) at Http.GET(Http.java:37) at Http.main(Http.java:326)java.lang.NullPointerException at Http.main(Http.java:330)Exception in thread "main"
你需要实现更复杂的socket穿透代理功能。或者你可以试试下面这个比较简单的方法:public static void main(String [] args){
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", "202.102.52.93");
System.getProperties().put("proxyPort", "3128"); String target = "http://www.google.com/search?q=java+book";
try {
URL url = new URL(target);
HttpURLConnection pconn = (HttpURLConnection)url.openConnection();
pconn.addRequestProperty("User-Agent","IcewolfHttp/1.0");
pconn.addRequestProperty("Accept","www/source; text/html; image/gif; */*");
pconn.connect();
System.out.println("Connect status:"+pconn.getResponseCode());
//if(HttpURLConnection.HTTP_ACCEPTED == pconn.getResponseCode())
//InputStream in = url.openConnection(); InputStream in = pconn.getInputStream();
System.out.println("Get status:"+pconn.getResponseCode());
BufferedInputStream buff = new BufferedInputStream(in);
Reader r = new InputStreamReader(buff);
int c = 0;
while ( (c = r.read()) != -1){
System.out.print((char)c);
} buff.close();
in.close();
pconn.disconnect();
}
catch (MalformedURLException mfe) {
System.err.println(target + " is not a parsable URL");
}
catch (IOException ioe) {
System.err.println(ioe);
}}
在结贴之前,再次感谢你,如今我想通过SOCKET去取数据,该怎样办?