分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

网络传输---HttpURLConnection

发布时间:2023-09-06 01:42责任编辑:彭小芳关键词:暂无标签

HttpURLConnection是java做网络传输的一种,一般用于做数据的传输如xml数据传输

  1.创建及配置:

    1.1创建一个url对象,并指定url的地址

URL url = new URL(urlString);

    1.2 对此地址所引用的远程对象的连接

 HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();

    1.3 对此连接进行配置

//设置HttpURLConnection参数 ???????????httpUrlConnection.setRequestMethod("POST"); ???????????// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 ???????????// http正文内,因此需要设为true, 默认情况下是false; ???????????httpUrlConnection.setDoOutput(true); ???????????// 设置是否从httpUrlConnection读入,默认情况下是true; ???????????httpUrlConnection.setDoInput(true); ???????????//设置不使用缓存 ???????????httpUrlConnection.setUseCaches(false); ???????????//设置发送请求为utf-8 ???????????httpUrlConnection.setRequestProperty("Content-type", "text/html;charset=utf-8"); ???????????//设置网络请求时间最多为5秒; ???????????httpUrlConnection.setConnectTimeout(5000); ???????????//读取网页请求结果时间为15秒 ???????????httpUrlConnection.setReadTimeout(25000);

    1.4 这些配置完成之后才能开启连接

// 连接,从上述url.openConnection()至此的配置必须要在connect之前完成, ???????????httpUrlConnection.connect();

  2.获得对HttpURLConnection远程对象连接的输出

//输出 ???????????OutputStream out = httpUrlConnection.getOutputStream(); ???????????//用到了缓存流,提高IO效率,由于数据为字符,用到字符转字节的包装流,并设置UTF-8编码 ???????????BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(out,"utf-8")); ???????????bout.write("demo"); ???????????bout.flush(); ???????????bout.close();

  3.获得对HttpURLConnection远程对象连接的输入结果

 //获得返回结果 ???????????if (httpUrlConnection.getResponseCode() == httpUrlConnection.HTTP_OK) {//判断状态码是否为200 ???????????????????InputStream in = httpUrlConnection.getInputStream(); ???????????????????BufferedReader reader = new BufferedReader(new InputStreamReader( ???????????????????????????in)); ???????????????????StringBuffer stringBuffer = new StringBuffer(); ???????????????????String str = ""; ???????????????????while ((str = reader.readLine()) != null) { ???????????????????????????stringBuffer.append(str+"\n"); ???????????????????} ???????????????????reader.close(); ???????????????????in.close(); ???????????????????return stringBuffer.toString(); ???????????}else{ ???????????????????return null; ???????????}

4.PS:用到HttpURLConnection对象时肯定存在相对应的url地址,此时需要服务器部署url资源,用服务器对指定的请求做处理

  

    

网络传输---HttpURLConnection

原文地址:https://www.cnblogs.com/future-eye/p/8447899.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved