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+" "); } reader.close(); in.close(); return stringBuffer.toString(); }else{ return null; }
4.PS:用到HttpURLConnection对象时肯定存在相对应的url地址,此时需要服务器部署url资源,用服务器对指定的请求做处理