public class HttpURLConnectionDemo {
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/day14_web/servlet/DemoServlet");
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
request(conn);
}
//获取服务器的响应
private static void response(HttpURLConnection conn) throws IOException{
//响应码
int code = conn.getResponseCode();
//响应码描述
String message = conn.getResponseMessage();
//响应头
String headerValue = conn.getHeaderField("Server");
//响应正文
InputStream in = conn.getInputStream();
byte b[] = new byte[1024];
int len = -1;
while((len=in.read(b))!=-1){
System.out.println(new String(b,0,len));
}
in.close();
conn.disconnect();
}
//向服务器发请求
private static void request(HttpURLConnection conn) throws IOException{
conn.setDoOutput(true);
//请求方式
conn.setRequestMethod("POST");
//请求头
conn.setRequestProperty("bigheader", "bigheadervalue");
//请求正文:请求参数。name=value
OutputStream out = conn.getOutputStream();
out.write("username=中国".getBytes());
int code = conn.getResponseCode();
System.out.println(code);
}
}
HttpURLConnection
最新推荐文章于 2012-09-14 23:26:09 发布