HttpURLConnection的get和post请求实例
2016-08-17 20:46
344 查看
get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
public class DemoConnection02 { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { String path = "图片路径"; //1, 得到URL对象 URL url = new URL(path); //2, 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //3, 设置提交方式 conn.setRequestMethod("GET"); //4, 获取响应信息 if(conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = is.read(buffer))!=-1) { baos.write(buffer, 0, len); } //截取图片名称 String fileName = path.substring(path.lastIndexOf("/")+1); FileOutputStream fos = new FileOutputStream("d:/"+fileName); fos.write(baos.toByteArray()); fos.close(); System.out.println("图片下载成功!!!"); } }
post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
public static void main(String[] args) throws Exception { String path = "http://localhost:8080/Day_28_Servlet/LoginServlet"; //1, 得到URL对象 URL url = new URL(path); //2, 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //3, 设置提交类型 conn.setRequestMethod("POST"); //4, 设置允许写出数据,默认是不允许 false conn.setDoOutput(true); conn.setDoInput(true);//当前的连接可以从服务器读取内容, 默认是true //5, 获取向服务器写出数据的流 OutputStream os = conn.getOutputStream(); //参数是键值队 , 不以"?"开始 os.write("useName=abc&usePwd=123".getBytes()); os.flush(); //6, 获取响应的数据 if(conn.getResponseCode()==200) { //得到服务器写回的响应数据 InputStream is = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = br.readLine(); System.out.println("响应内容为: " + str); } }
相关文章推荐
- Android 实时加载网络新闻
- 完美网络
- TCP知识2
- https 和 http 端口号是多少
- HTTP缓存策略
- 浅析:setsockopt()改善socket网络程序的健壮性
- 杂记1:android广播监听实时监听网络,以及回调机制应用
- TCP/IP协议中backlog参数
- HTTP的长连接和短连接
- HTTP Keep-Alive模式
- TCP知识1
- LoadImage一个从网络访问图片,并存到缓存(内存,磁盘)直接可以用
- 征稿,网络安全实战类文章
- 【深度学习】生成对抗网络Generative Adversarial Nets
- Mac安装VM虚拟机
- 将http地址的图片写入指定路径下
- TCP长连接与短连接的区别
- 深度学习笔记3:实现一个卷积神经网络
- 长连接短连接socket及windows连接数限制配置
- httpd设置HTTPS双向认证