HttpURLConnection

来源:互联网 发布:yy淘宝刷钻平台网址 编辑:程序博客网 时间:2024/04/30 12:40
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=valueOutputStream out = conn.getOutputStream();out.write("username=中国".getBytes());int code = conn.getResponseCode();System.out.println(code);}}

原创粉丝点击