/**
* 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();
}
socket模拟http请求
最新推荐文章于 2024-07-04 09:15:00 发布