java中发送Http请求的方法很多,可以使用开源框架如httpclient,URLConnection的相关函数或者直接使用Socket来发送。相对于前两种,直接使用Socket发送http请求可以说是最底层的方式,其他方式或多或少的对该方式进行了封装。
POST请求格式如下:
POST /login.php HTTP/1.1 *
Host: www.webserver.com:80 *
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/2008052906 Firefox/3.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,**; q=.2\r\n");
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://www.vckbase.com/
Cookie: ASPSESSIONIDCSAATTCD=DOMMILABJOPANJPNNAKAMCPK
Content-Type: application/x-www-form-urlencoded *
Content-Length: 79
userid=aaaaaaa&password=01234567890&gclsid=501&imageField3.x=43&imageField3.y=11
在参数上一定要注意的是,一定要有一个空行,表示请求头结束,否则,服务端无法判断请求头是否结束,从而挂掉。另外需要特别注意的是Content-Length后的数据长度值一定要正确,是获取的数据体部分的字节长度,具体就是 userid=aaaaaaa&password=01234567890&gclsid=501&imageField3.x=43&imageField3.y=11 这部分对应的数据。
GET Java代码
- try
{ -
Socket s = new Socket("www.pconline.com.cn",80); -
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(),"GBK")); -
OutputStream out = s.getOutputStream(); -
StringBuffer sb = new StringBuffer("GET /index.html HTTP/1.1\r\n"); -
sb.append("User-Agent: Java/1.6.0_20\r\n"); -
sb.append("Host: www.pconline.com.cn:80\r\n"); -
sb.append("Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2\r\n"); -
sb.append("Connection: Close\r\n"); -
sb.append("\r\n"); -
out.write(sb.toString().getBytes()); -
String tmp = ""; -
while((tmp = br.readLine())!=null){ -
System.out.println(tmp); -
} -
out.close(); -
br.close(); -
-
} catch (UnknownHostException e) { -
// TODO Auto-generated catch block -
e.printStackTrace(); -
} catch (IOException e) { -
// TODO Auto-generated catch block -
e.printStackTrace(); -
}
POST请求之Java代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TestPost {
public static void main(String args[]){
try
{
//Post请求格式如下:
String postStr = "account=abc&password=123456789";
int postStrLen = postStr.length();
StringBuffer post = new StringBuffer("POST /login.php HTTP/1.1\r\n");
post.append("Host: 127.0.0.1:80\r\n");
post.append("Accept: text/html\r\n");
post.append("Connection: Close\r\n");
post.append("Content-Length: "+postStrLen+"\r\n");
post.append("Content-Type: application/x-www-form-urlencoded\r\n");//*
post.append("\r\n");
post.append(postStr);
System.out.println(post);//post
// HTTP POST其他请求头如下
// post.append("User-Agent: Java/1.6.0_20\r\n");
// post.append("Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7");
Socket socket=new Socket("127.0.0.1",80);
PrintWriter os=new PrintWriter(socket.getOutputStream());//用于发送
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));//用于接收
os.println(post);//发送post请求
os.flush();
System.out.println("Server:");
System.out.println("end");
}catch(Exception e){
e.printStackTrace();
}
}
}