ITeye博客

socket模拟http请求

hepx · 2012-08-16 13:21 · web · 编程语言 · Markdown

/**
 * socket模拟http 请求
 * @author xixi
 * 注意:请求的目标端要实现GET和POST的方法。IP和端口适自己的情况定
 * 
 * 用来测试,没有封装。
 */
public static void doGet(){
try {
//如果传中文参数请转码
String data = "pid=1002&pcode=K001001";
// Create a socket to the host
String hostname = "localhost";
int port = 8088;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
  
// Send header
String path = "/kinyb/doMW2?"+data;
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
wr.write("GET "+path+" HTTP/1.0\r\n");
wr.write("\r\n");

wr.flush();
  
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
 * socket模拟http post 请求
 * @author xixi
 */
public static void doPost(){
try {
  
String data = "pid=1002&pcode=K001001";
// Create a socket to the host
String hostname = "localhost";
int port = 8088;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
  
// Send header
String path = "/kinyb/doMW2";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "GBK"));
wr.write("POST "+path+" HTTP/1.0\r\n");
wr.write("Content-Length: "+data.length()+"\r\n");
        wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("\r\n");
// Send data
wr.write(data);
wr.flush();
  
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream(),"GBK"));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
 * @author xixi
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
//doGet();
doPost();

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。