当前位置: 代码迷 >> Android >> 请问HttpUrlConnection上传文件有关问题
  详细解决方案

请问HttpUrlConnection上传文件有关问题

热度:15   发布时间:2016-04-28 07:29:29.0
请教HttpUrlConnection上传文件问题
已经加了<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
代码:地址有效,执行到DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());时抛出异常,不知道怎么回事?
java.io.IOException
 public void onFileItemClick(String filename)
   {
   String uploadUrl = "http://192.168.1.103:8080/uhonesty/uploadFile";
   String end = "\r\n";
   String twoHyphens = "--"; // 两个连字符
   String boundary = "******"; // 分界符的字符串
   try
   {
   URL url = new URL(uploadUrl);
   HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
   httpURLConnection.setDoInput(true);
   httpURLConnection.setDoOutput(true);
   httpURLConnection.setUseCaches(false);
   httpURLConnection.setRequestMethod("POST");
   // 设置Http请求头
   httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
   httpURLConnection.setRequestProperty("Charset", "UTF-8");
   //  必须在Content-Type 请求头中指定分界符中的任意字符串
   httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
  
   //定义数据写入流,准备上传文件
   DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());//此处抛出异常,java.io.IOException
   dos.writeBytes(twoHyphens + boundary + end);
   //设置与上传文件相关的信息
   dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""
   + filename.substring(filename.lastIndexOf("/") + 1)
   + "\"" + end);
   dos.writeBytes(end);

   FileInputStream fis = new FileInputStream(filename);
   byte[] buffer = new byte[8192]; // 8k
   int count = 0;
   // 读取文件夹内容,并写入OutputStream对象
   while ((count = fis.read(buffer)) != -1)
   {
   dos.write(buffer, 0, count);
   }
   fis.close();
   dos.writeBytes(end);
   dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
   dos.flush();
   // 开始读取从服务器传过来的信息
   InputStream is = httpURLConnection.getInputStream();
   InputStreamReader isr = new InputStreamReader(is, "utf-8");
   BufferedReader br = new BufferedReader(isr);
   String result = br.readLine();

   Toast.makeText(this, result, Toast.LENGTH_LONG).show();
   dos.close();
   is.close();
   }
   catch (Exception e)
   {
   setTitle(e.getMessage());
   }
   }

------解决方案--------------------
把网络操作放到新线程里试试。2.3跟4.0一个明显区别就是网络操作能不能放在UI主线程了。
------解决方案--------------------
4.0以上 所有网络操作都要放在线程里
------解决方案--------------------
4.0不能放在主线程里
------解决方案--------------------
像这种耗时的操作,需要另起一个线程,不能在主线程(ui线程)执行。在4.0以前没有这个限制,但4.0后就有了,也就是dnr
  相关解决方案