socket模拟http请求


/**
 * 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();


}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值