Java 如何在android中通过文件上传发送常规post键/值对

Java 如何在android中通过文件上传发送常规post键/值对,java,android,api,file-upload,Java,Android,Api,File Upload,我有一个通过post上传照片的功能。我可以很好地上传文件,但不确定如何添加更多的键/值对来发布,基本上我需要随文件数据提供一个API键和会话键,方法如下所示 public ContainerData submitPhoto(FileInputStream fileInputStream, String sessionKey) { try { URL url = new URL(API_URL); HttpURLConnection conn = nu

我有一个通过post上传照片的功能。我可以很好地上传文件,但不确定如何添加更多的键/值对来发布,基本上我需要随文件数据提供一个API键和会话键,方法如下所示

public ContainerData submitPhoto(FileInputStream fileInputStream, String sessionKey) {

    try {

        URL url = new URL(API_URL);

        HttpURLConnection conn = null;

        if (url.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }


        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        // HttpURLConnection conn = (HttpURLConnection)
        // connectURL.openConnection();

        // Allow Inputs
        conn.setDoInput(true);

        // Allow Outputs
        conn.setDoOutput(true);

        // Don't use a cached copy.
        conn.setUseCaches(false);

        // Use a post method.
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "Keep-Alive");

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

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

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

        // create a buffer of maximum size

        int bytesAvailable = fileInputStream.available();
        int maxBufferSize = 1028;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];

        // read file and write it into form...

        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            /*
             * dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary
             * + twoHyphens + lineEnd);
             */
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        dos.flush();
        // Log.d(TAG, "  dos5: " + dos.toString());
        InputStream is = conn.getInputStream();
        // retrieve the response from server
        int ch;

        StringBuffer b = new StringBuffer();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        String stringResponse = b.toString();
        // Log.d(TAG, "http response for upload" + s);
        dos.close();

        Gson gson = new GsonBuilder().serializeNulls().create();
        responseObject = gson.fromJson(stringResponse,ContainerData.class);

        JSONObject data = new JSONObject(stringResponse);
        String dataResponse = data.getString("data");
        responseObject.setDataString(dataResponse);


    } catch (JSONException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return responseObject;

}
指定格式。从链接:

Content-type: multipart/form-data, boundary=AaB03x

--AaB03x
content-disposition: form-data; name="field1"

Joe Blow
--AaB03x
content-disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--
您的代码还有两个问题:

1) 我发现在每次迭代时重新创建缓冲区既麻烦又缓慢。只需在循环之前将其调暗到最大大小,然后重新使用即可

2) 另外,直接发送数据字节可能会有风险(如果图片的两个字节的值与分隔符的值相同怎么办?我建议使用base64编码。

指定格式。从链接:

Content-type: multipart/form-data, boundary=AaB03x

--AaB03x
content-disposition: form-data; name="field1"

Joe Blow
--AaB03x
content-disposition: form-data; name="pics"; filename="file1.txt"
Content-Type: text/plain

... contents of file1.txt ...
--AaB03x--
您的代码还有两个问题:

1) 我发现在每次迭代时重新创建缓冲区既麻烦又缓慢。只需在循环之前将其调暗到最大大小,然后重新使用即可

2) 另外,直接发送数据字节可能有风险(如果图片中的两个字节的值与分隔符的值相同怎么办?我建议使用base64编码