android中的HttpURLConnection参数传递问题?

时间:2011-05-25 08:51:55

标签: android android-layout

HI,

我使用以下部分代码将文件上传到服务器,连同此文件我需要发送一些关于此文件的参数,我不知道如何将参数与文件一起发送,但我可以上传文件。

               FileInputStream fileInputStream = new FileInputStream(sourceFile);
       URL url = new URL(upLoadServerUri);
       conn = (HttpURLConnection) url.openConnection(); 

       conn.setDoInput(true); // Allow Inputs
       conn.setDoOutput(true); // Allow Outputs
       conn.setUseCaches(false); // Don't use a Cached Copy
       conn.setRequestMethod("POST");

       conn.setRequestProperty("Connection", "Keep-Alive");
       conn.setRequestProperty("ENCTYPE", "multipart/form-data");

       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);


       dos = new DataOutputStream(conn.getOutputStream());

       dos.writeBytes(twoHyphens + boundary + lineEnd);
       dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""+ fileName + "\"" + lineEnd);
       dos.writeBytes(lineEnd);

       bytesAvailable = fileInputStream.available(); 



       bufferSize=(int)sourceFile.length();


       buffer = new byte[1024];
       int len;
       int state=0;
       while((len=fileInputStream.read(buffer))>0){
           state=state+len;
           dos.write(buffer);
           publishProgress(state);
       }

       dos.writeBytes(lineEnd);
       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

       // Responses from the server (code and message)
       serverResponseCode = conn.getResponseCode();
       String serverResponseMessage = conn.getResponseMessage();


       // close streams
       Log.i("Upload file to server", fileName + " File is written");
       fileInputStream.close();
       dos.flush();
       dos.close();
      } catch (MalformedURLException ex) {
       ex.printStackTrace();
       Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
      } catch (Exception e) {
       e.printStackTrace();
      }
    //this block will give the response of upload link
      try {
       BufferedReader rd = new BufferedReader(new InputStreamReader(conn
         .getInputStream()));

       while ((line = rd.readLine()) != null) {
        Log.i("Huzza", "RES Message: " + line);


       }
       rd.close();
      } catch (IOException ioex) {
       Log.e("Huzza", "error: " + ioex.getMessage(), ioex);

      }

如果有人知道问题会帮助我。

1 个答案:

答案 0 :(得分:0)

将http客户端与多部分实体一起使用。你需要额外的库。

这是一篇关于如何做到这一点的好文章:

MultipartEntity