socket 发送http请求
来源:互联网 发布:属于网络层协议的是 编辑:程序博客网 时间:2024/04/19 09:24
一、发送Get请求
import java.net.*;import java.io.*;public class URLSender { /** * @param args */ public static void main(String[] args) throws IOException { try { Socket socket = new Socket("www.nwu.edu.cn", 80); boolean autoflush = true; PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.println("Host: nwu.edu.cn"); out.println("Connection: Close"); out.println(); //read the response boolean loop = true; StringBuffer sb = new StringBuffer(8096); while (loop) { if (in.ready()) { int i = 0; while (i != -1) { i = in.read(); sb.append((char) i); } loop = false; } //Thread.currentThread().sleep(50); } //display the response to the out console System.out.println(sb.toString()); socket.close(); } catch (UnknownHostException e) { System.err.println("Don't know about host: Victest."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: Victest."); System.exit(1); } }}
2、用Socket发送一个POST请求
try {
// Construct data
String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
// Create a socket to the host
String hostname = "hostname.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
// Send header
String path = "/servlet/SomeServlet";
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
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()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
- socket 发送http请求
- socket发送http请求
- socket 发送http请求
- c socket 发送http请求
- 使用SOCKET发送HTTP请求
- c++ socket 发送HTTP请求
- java socket发送http请求
- Network:socket发送http请求
- C socket 发送HTTP请求
- 使用Socket发送Http请求
- 使用Socket发送Http请求
- socket模拟http发送请求
- c++ socket发送http请求
- 使用socket发送http请求(GET/POST)
- socket 发送http请求 参数详细说明
- 使用socket发送http请求(GET/POST)
- c socket 发送http请求 (一)
- 使用socket发送http请求(GET/POST)
- CBR简介
- 清除页面缓存的方法总结
- SAP中PATH和TCODE的相互查找
- HTTP请求模型和头信息
- 第七章 使用结构组合数据
- socket 发送http请求
- J2EE教学体会
- stl作为局部变量的内存问题
- 风险投资=骗子?
- Symbian GUI 应用资源文件介绍 zz
- 如何隐藏win32 console application的console窗口
- SAP 标准倒EXCEL的FM
- 通过阵地攻坚战谈项目调研的方法
- 主流搜索引擎对用户点选命中的处理