服务器代码:
package com.infohold.http;
import java.net.*;
public class WebServer {
public static void main(String args[]) {
int i=1, PORT=80;
ServerSocket server=null;
Socket client=null;
try {
server=new ServerSocket(PORT);
System.out.println("Web Server is listening on port "+server.getLocalPort());
for (;;) {
client=server.accept(); // 接受客户机的连接请求
new ConnectionThread(client,i).start();
i++;
}
} catch (Exception e){
System.out.println(e);
}
}
}
package com.infohold.http;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
class ConnectionThread extends Thread {
Socket client; // 连接Web浏览器的socket字
int counter; // 计数器
public ConnectionThread(Socket cl,int c) {
client=cl;
counter=c;
}
public void run() {
try {
String destIP=client.getInetAddress().toString(); // 客户机IP地址
int destport=client.getPort(); // 客户机端口号
System.out.println("Connection "+counter+":connected to "+destIP+" on port "+destport+".");
PrintStream outstream=new PrintStream(client.getOutputStream());
DataInputStream instream=new DataInputStream(client.getInputStream());
String inline=instream.readLine(); // 读取Web浏览器提交的请求信息
System.out.println("Received:"+inline);
if (getrequest(inline)) { // 如果是GET请求
String filename=getfilename(inline);
File file=new File("D:/temp/"+filename);
if (file.exists()) { // 若文件存在,则将文件送给Web浏览器
System.out.println(filename+" requested.");
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME_version:1.0");
outstream.println("Content_Type:text/html");
int len=(int)file.length();
outstream.println("Content_Length:"+len);
outstream.println("");
//outstream.println("{\"data\":{\"message\":[{\"cbsMessage\":{\"header\":{\"system_id\":\"00001\",\"compress\":\"0\"},\"transaction\":{\"code\":\"T000011\",\"time\":\"1350549273\",\"sequence\":\"20120622123456\"},\"body\":\"eyJPcmRlcklkIjoiQzAwMDAxIiwiQXJlYUlkIjoiMCIsIkNoYW5uZWwiOiIwMSIsIlRpY2tldHMiOlt7IlRpY2tldE5vIjoiMTAwMDAwMDA4OCIsIlR5cGUiOiIwMCIsIlByaWNlIjoiMTAwLjAwIiwiQ2hhcmdlIjoiMC41In1dLCJUeXBlIjoiOTkiLCJUaWNrZXRObyI6IjAwMDAwNjUiLCJDaGVja0RhdGUiOiIyMDEyLTEwLTIyIiwiRGV2aWNlIjoiMDc1NDM0NDU0IiwiT3RoZXJObyI6IjA2NTUiLCJPdGhlckJyY05vIjoiMDM0NDMzIiwiUHJpY2UiOiIxMDAiLCJSZWZ1bmREYXRlIjoiMjAxMi0xMC0yMiIsIlBheURhdGUiOiIyMDEyLTEwLTIyIiwiVmFsaWREYXRlIjoiMjAxMi0xMC0yMiJ9\"}}]}}");
// outstream.println("{\"data\": {\"messages\": {\"cbsMessage\": [{\"header\": {\"system_id\": \"T\",\"encrypt\": \"0\",\"compress\": \"0\"},\"transaction\": {\"code\": \"T000011\",\"time\": \"\",\"sequence\": \"20120622123456\"},\"body\":\"eyJhcmVhX2lkIjogIjAiLCJjaGFubmVsIjogIjIiLCJ0aWNrZXRzIjogW3sidGlja2V0X25vIjogIjEyMzQ1Njc4OTAiLCJ0aWNrZXRfdHlwZSI6ICIwIiwidGlja2V0X3ByaWNlIjogMTU2LjAwLCJzZXJ2aWNlX2NoYXJnZSI6IDEuNTZ9XSwiYmlsbF9ubyI6ICJkZDEyMzQ1NiIsInRpY2tldF9kYXRlIjogIjIwMTItMTAtMTAgMTA6MTA6MTAiLCJ2YWxpZF9kYXRlIjogIjIwMTItMTAtMTMgMTA6MTA6MTAiLCJ0aWNrZXRfbnVtYmVyIjogIjEyMzQ1Njc4OTAiLCJ0aWNrZXRfdHlwZSI6ICIwIiwiZGV2aWNlX2lkIjogImRYakZsNDMxVXQxMjMiLCJjaGVja19kYXRlIjogIjIwMTItMTAtMTEgMTA6MTA6MTAiLCJwcmljZSI6IDE1NiwiY2FyZF9ubyI6ICJkc2YxMjMiLCJjYXJkX3Byb3ZpZGVyX25vIjogImZrZjEyMyIsInJlZnVuZF9jaGFubmVsIjogIjIiLCJyZWZ1bmRfZGF0ZSI6ICIyMDEyLTEwLTExIDEwOjEwOjEwIiwib3JkZXJfaWQiOiAiZGQxMjM0NTYiLCJ1bmlwYXlfc2VxIjogInlsc2VxIiwidW5pcGF5X3RyYWNlX25vIjogInlsenpoIiwgInVuaXBheV90cmFjZV9kYXRlIjogIjIwMTItMTAtMTEgMTA6MTA6MTAifQ==\"}]}}}");
outstream.println("{\"return_message\": \"success\", \"data\": {\"count\": 1, \"messages\": [{\"cbsMessage\": {\"body\": \"eyJhcmVhX2lkIjoiQzAwMDAxIiwiY2hhbm5lbCI6IjAiLCJ0aWNrZXRzIjpbeyJ0aWNrZXRfbm8i\r\nOiIxMDAwMDAwNTMyIiwidGlja2V0X3R5cGUiOiJXVDAwMSIsInRpY2tldF9wcmljZSI6IjU5OTk5\r\nOTk5LjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTMzIiwidGlja2V0X3R5cGUiOiJXVDAwMSIs\r\nInRpY2tldF9wcmljZSI6IjU5OTk5OTk5LjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTM1Iiwi\r\ndGlja2V0X3R5cGUiOiJXVDAwMSIsInRpY2tldF9wcmljZSI6IjU5OTk5OTk5LjAwIn0seyJ0aWNr\r\nZXRfbm8iOiIxMDAwMDAwNTM2IiwidGlja2V0X3R5cGUiOiJXVDAwMSIsInRpY2tldF9wcmljZSI6\r\nIjU5OTk5OTk5LjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTM3IiwidGlja2V0X3R5cGUiOiJX\r\nVDAwMSIsInRpY2tldF9wcmljZSI6IjU5OTk5OTk5LjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAw\r\nNTM5IiwidGlja2V0X3R5cGUiOiJXVDAwMSIsInRpY2tldF9wcmljZSI6IjU5OTk5OTk5LjAwIn0s\r\neyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTQwIiwidGlja2V0X3R5cGUiOiJXVDAwMSIsInRpY2tldF9w\r\ncmljZSI6IjU5OTk5OTk5LjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTUyIiwidGlja2V0X3R5\r\ncGUiOiJGVDAwMSIsInRpY2tldF9wcmljZSI6IjQwMDAwMDAwLjAwIn0seyJ0aWNrZXRfbm8iOiIx\r\nMDAwMDAwNTU0IiwidGlja2V0X3R5cGUiOiJGVDAwMSIsInRpY2tldF9wcmljZSI6IjQwMDAwMDAw\r\nLjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTU1IiwidGlja2V0X3R5cGUiOiJGVDAwMSIsInRp\r\nY2tldF9wcmljZSI6IjQwMDAwMDAwLjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTU2IiwidGlj\r\na2V0X3R5cGUiOiJGVDAwMSIsInRpY2tldF9wcmljZSI6IjQwMDAwMDAwLjAwIn0seyJ0aWNrZXRf\r\nbm8iOiIxMDAwMDAwNTU3IiwidGlja2V0X3R5cGUiOiJGVDAwMSIsInRpY2tldF9wcmljZSI6IjQw\r\nMDAwMDAwLjAwIn0seyJ0aWNrZXRfbm8iOiIxMDAwMDAwNTU4IiwidGlja2V0X3R5cGUiOiJGVDAw\r\nMSIsInRpY2tldF9wcmljZSI6IjQwMDAwMDAwLjAwIn1dLCJiaWxsX25vIjoiIiwidGlja2V0X2Rh\r\ndGUiOiIyMDEyLTEwLTI0IDExOjIzOjQyIiwidmFsaWRfZGF0ZSI6IjIwMTItMTAtMjQgMDA6MDA6\r\nMDAifQ==\", \"header\": {\"encrypt\": \"0\", \"system_id\": \"T\", \"compress\": \"0\"}, \"transaction\": {\"code\": \"EBP0001\", \"sequence\": \"1351049022514945\", \"time\": \"1351049022\"}}}]}, \"return_code\": 0}");
//sendfile(outstream,file); // 发送文件
outstream.flush();
} else { // 文件不存在时
System.out.println("erro requested.");
// String notfound="<html><head><title>Not Foundmm</title></head><body><h1>Error 404-file not found</h1></body></html>";
// outstream.println("HTTP/1.0 404 no found");
// outstream.println("Content_Type:text/html");
// outstream.println("Content_Length:"+notfound.length()+2);
outstream.println("HTTP/1.0 200 OK");
outstream.println("MIME_version:1.0");
outstream.println("");
outstream.println("{\"data\":{\"message\":{\"cbsMessage\":{\"header\":{\"system_id\":\"00001\",\"compress\":\"0\"},\"transaction\":{\"code\":\"T000011\",\"time\":\"1350549273\",\"sequence\":\"20120622123456\"}},\"body\":\"eyJPcmRlcklkIjoiQzAwMDAxIiwiQXJlYUlkIjoiMCIsIkNoYW5uZWwiOjAxLCJUaWNrZXRzIjpbIlRpY2tldE5vIjoiMTAwMDAwMDA4OCIsIlR5cGUiOiIwMCIsIlByaWNlIjoiMTAwLjAwIiwiQ2hhcmdlIjoiMC41Il0sIlR5cGUiOiI5OSIsIlRpY2tldE5vIjoiMDAwMDA2NSIsIkNoZWNrRGF0ZSI6IjIwMTItMTAtMjIiLCJEZXZpY2UiOiIwNzU0MzQ0NTQiLCJPdGhlck5vIjoiMDY1NSIsIk90aGVyQnJjTm8iOiIwMzQ0MzMiLCJQcmljZSI6IjEwMCIsIlJlZnVuZERhdGUiOiIyMDEyLTEwLTIyIiwiUGF5RGF0ZSI6IjIwMTItMTAtMjIiLCJWYWxpZERhdGUiOiIyMDEyLTEwLTIyIn0=\"}}}}");
//outstream.println("{\"cbsMessage\":{\"header\":{\"system_id\":\"T\",\"encrypt\":\"0\",\"compress\":\"0\"},\"transaction\":{\"code\":\"EBP0001\",\"time\":\"1350907856\",\"sequence\":\"13509078560716060\"},\"body\":\"eyJhcmVhX2lkIjoiQzAwMDAxIiwiY2hhbm5lbCI6IjAiLCJ0aWNrZXRfdG90YWwiOjE5OTk5OTk5\r\nOC4wMCwidGlja2V0cyI6WyIxMDAwMDAwMDg4IiwiMTAwMDAwMDA4OSJdLCJpbmRpY2F0b3IiOiIw\r\nIiwidGlja2V0X2RhdGUiOiIyMDEyLTEwLTIyIDIwOjEwOjU2IiwidmFsaWRfZGF0ZSI6IjIwMTIt\r\nMTAtMjIgMDA6MDA6MDAifQ\u003d\u003d\"}}");
outstream.flush();
}
}
long m1=1;
while (m1<11100000) {m1++;} // 延时
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/* 获取请求类型是否为“GET” */
boolean getrequest(String s) {
if (s.length()>0){
if (s.substring(0,3).equalsIgnoreCase("GET"))
return true;
}
return false;
}
/* 获取要访问的文件名 */
String getfilename(String s) {
String f=s.substring(s.indexOf(' ')+1);
f=f.substring(0,f.indexOf(' '));
try {
if (f.charAt(0)=='/')
f=f.substring(1);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception:"+e);
}
if (f.equals("")) f="index.html";
System.out.println(f);
return f;
}
/*把指定文件发送给Web浏览器 */
void sendfile(PrintStream outs,File file) {
try {
DataInputStream in=new DataInputStream(new FileInputStream(file));
int len=(int)file.length();
byte buf[]=new byte[len];
in.readFully(buf);
outs.write(buf,0,len);
outs.flush();
in.close();
} catch (Exception e) {
System.out.println("Error retrieving file.");
System.exit(1);
}
}
}
客户端代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebClient{
public static String getWebContent(String urlString,final String charset,int timeout) throws IOException {
if(urlString==null||urlString.length()==0) {
return null;
}
urlString = (urlString.startsWith("http://") || urlString
.startsWith("https://")) ? urlString : ("http://" + urlString)
.intern();
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn
.setRequestProperty(
"User-Agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");//增加报头,模拟浏览器,防止屏蔽
conn.setRequestProperty("Accept", "text/html");//只接受text/html类型,当然也可以接受图片,pdf,*/*任意,就是tomcat/conf/web里面定义那些
conn.setConnectTimeout(timeout);
try {
if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK) {
return null;
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input,
charset));
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
if(reader!=null) {
reader.close();
}
if(conn!=null) {
conn.disconnect();
}
return sb.toString();
}
public static String getWebContent(String urlString) {
String dealUrl="";
try {
dealUrl= getWebContent(urlString,"iso-8859-1",5000);
} catch (Exception e) {
e.printStackTrace();
}
return dealUrl;
}
public static void main(String[]args){
String s = getWebContent("http://127.0.0.1/index2.html");
try {
s = new String(s.getBytes("iso-8859-1"),"gb2312");
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s);
}
}