我在java中很新,这是我的代码。 我想写一个简单的java套接字浏览器 你进入"主持人"和"路径"它会发送该主机的http请求,然后将html文件或图片等存储在您的计算机中。 问题是套接字接收http响应,但程序不能保存任何东西。程序生成文件,但文件是空的。 我知道这是底线的问题,但我不知道解决方案? while((a = s.getInputStream()。read(inputline))!= -1) 任何帮助,请
public class explorer {
private static Socket s;
@SuppressWarnings("unused")
public static void main(String[] args)
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String host ="google.com";
String path ="/images/srpr/logo11w.png";
s = new Socket(host, 80);
PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.println("GET " + path + " HTTP/1.1");
pw.println("Host:"+host);
pw.println("");
pw.flush();
String[] parts = path.split("/");
String filename = parts[parts.length-1];
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
byte [] inputline =new byte[2000];
byte [] inputline2 =new byte[300000];
int a=0;
int resultlenght=0;
FileOutputStream fos=new FileOutputStream("C:/Users/mahmoud/Desktop/"+filename);
while ((a=s.getInputStream().read(inputline)) != -1)
{
System.arraycopy(inputline,0, inputline2,resultlenght,a);
resultlenght+=a;
}
for(a=0;;a++)
{
if(inputline2[a]==13 && inputline2[a+1]==10 && inputline2[a+2]==13 && inputline2[a+3]==10)
{
break;
}
}
byte [] inputline3 =new byte[300000];
System.arraycopy(inputline2, a+4, inputline3, 0, inputline2.length-a-4);
fos.write(inputline3,0,inputline3.length);
fos.flush();
fos.close();
in.close();
}
catch (UnknownHostException e) {
System.out.println("Exception: "+e);
}
catch (Exception ex) {
System.out.println("Exception: "+ex);
}
}
}
答案 0 :(得分:0)