这个程序只输出一行字符串,可能是代码写错了,看得懂这个程序是啥作用的高手帮我改过来好吗,谢谢阿。
import java.net.*;
import java.io.*;
public class netConnect
{
private static final String AGENT_NAME="java-alta-search";
private static final String AGENT_VERSION="1.0";
private static final String SEARCH_URL="http://www.altavista.digital.com/cgi-bin/query";
private int totalHits=0;
private StringBuffer outputList=new StringBuffer();
public static void main(String as[])
{
if(as.length == 0)
{
System.out.println("usage:AltaVistaList search string");
System.exit(1);
}
netConnect runApp=new netConnect(as);
runApp.printOutput(System.out);
System.exit(0);
}
public netConnect(String[]as)
{
String hitData;
int startHits=0;
String searchSyntax=createQuery(as);
URLConnection.setDefaultRequestProperty("user-Agent",AGENT_NAME+"/"+AGENT_VERSION);
while(true)
{
hitData=getPage(SEARCH_URL+"?"+searchSyntax+startHits);
hitData=getHits(hitData);
if(hitData!=null)
{
outputList.append(hitData+"\n");
startHits+=10;
}
else
break;
}
}
protected String createQuery(String searchTokens[])
{
StringBuffer searchString =new StringBuffer();
for(int index=0;index<searchTokens.length;index++)
{
searchString.append(searchTokens[index]);
if(index<searchTokens.length-1)
{
searchString.append("");
}
}
String encodedsearchString=URLEncoder.encode(searchString.toString());
return "what=web&fmt=c&pg=q&q="+encodedsearchString+"&stq=";
}
protected String getPage(String url)
{
StringBuffer page=new StringBuffer();
String nextLine;
try
{
URL urlObj=new URL(url);
URLConnection agent=urlObj.openConnection();
DataInputStream input=new DataInputStream(agent.getInputStream());
while((nextLine=input.readLine())!=null)
{
page.append(nextLine+"\n");
}
input.close();
}catch(MalformedURLException e)
{
System.out.println("badly formed url:"+e);
}catch(IOException e)
{
System.out.println("Failed I/O:"+e);
}
return page.toString();
}
protected String getHits(String hitPage)
{
int first,last;
int notFound=-1;
String hitSection=null;
first=hitPage.indexOf("<pre>")+"<pre>".length();
first=hitPage.indexOf("<a href=",first);
last=hitPage.indexOf("<pre>");
if(last<first)
return hitSection;
if(first == notFound||last == notFound)
{
System.err.println("bad search page format");
return hitSection;
}
hitSection=hitPage.substring(first,last);
first=last=0;
totalHits+=1;
while((last=hitSection.indexOf("\n",first))!=notFound)
{
first=hitSection.indexOf("<a href=",last);
if(first!=(last+1))
{
return hitSection.substring(0,last);
}
else
totalHits+=1;
}
return hitSection;
}
public void printOutput(PrintStream sendOutput)
{
sendOutput.print(AGENT_NAME+totalHits+outputList);
}
}