Android网络连接2——HttpURLConnection

    HttpURLConnection类是URL代表的网络资源与应用程序的连接。应用程序通过HttpURLConnection对象向服务器发送,读取URL指定的网络资源。

    使用步骤:

   1、创建URL对象

   2、通过url.openConnection()方法创建URLConnection对象

   3、设置URLConnection的参数和普通请求属性

  

		//1、创建URL对象
			URL url = new URL("http://192.168.70.113:8008/upload/uploadAction.do");
			//2、获得HttpUrlConnection对象
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			//3、设置请求方法类型,注意:必须大写
			httpURLConnection.setRequestMethod("POST");
			//4、设置参数属性
			//向服务器发送请求数据
			httpURLConnection.setDoOutput(true);
			//获取服务器的返回数据
			httpURLConnection.setDoInput(true);
			//禁止httpURLConnection使用缓存
			httpURLConnection.setUseCaches(false);
			//
			httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
			httpURLConnection.setRequestProperty("Charset", "UTF-8");
			//设置实体消息的类型,"application/x-www-form-urlencoded" 表示实体类型的自定义表单
//			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置类型为上传图片
			httpURLConnection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			//5、获取到服务端的输入输出流
		        InputStream is = httpURLConnection.getInputStream();
		        OutputStream out = httpURLConnection.getOutputStream();
                        //6、关闭流
                        is.close();out.close();

附件为上传下载案例:

猜你喜欢

转载自lydia-fly.iteye.com/blog/2033391