Android:使用参数将文件发送到服务器

时间:2017-09-22 12:06:10

标签: android post httpurlconnection

我决定重写我的旧代码,因为现在不推荐使用HttpPost,HttpResponse和HttpEntity。这是我的旧代码:

private static String uploadFile(String token, File tempFile, String uploadUrl, final String fileName)
        throws IOException, ExecutionException, InterruptedException {

    try {
        FileInputStream in = new FileInputStream(tempFile);
        byte[] fileBytes = org.apache.commons.io.IOUtils.toByteArray(in);
        in.close();

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("token", new StringBody(token, ContentType.TEXT_PLAIN));
        builder.addPart("name", new StringBody(fileName, ContentType.TEXT_PLAIN));
        builder.addPart("file", new ByteArrayBody(fileBytes, fileName));
        builder.addPart("fileType", new StringBody("IMAGE", ContentType.TEXT_PLAIN));
        HttpPost postRequest = new HttpPost(uploadUrl);
        postRequest.setEntity(builder.build());

        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        org.apache.http.HttpResponse response = httpClient.execute(postRequest);
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {
            HttpEntity urlEntity = response.getEntity();
            String str = org.apache.commons.io.IOUtils.toString(urlEntity.getContent());
            JsonObject jsonObject = new JsonParser().parse(str).getAsJsonObject();
            String Url = jsonObject.get("url").getAsString();
            String blobKey = jsonObject.get("key").getAsString();


            return Url;

        } 
    }
}

所以,现在我正在寻找一些替代方案。我期待HttpURLConnection,但有没有办法添加参数来请求? 我会很高兴得到任何帮助或暗示

1 个答案:

答案 0 :(得分:2)

完全工作的代码

public class FileUploader {
    private static final String LINE_FEED = "\r\n";
    private String boundary;
    private HttpURLConnection httpConn;
    private String charset = "UTF-8";
    private OutputStream outputStream;
    private PrintWriter writer;

    public String worker(String url, String params) {
        String requestURL = url;
        try {
            MultipartUtility multipart = new MultipartUtility(requestURL, charset);
            try {
                JSONObject obj = new JSONObject(params);
                Iterator<String> iter = obj.keys();
                while (iter.hasNext()) {
                    String key = iter.next();

                    try {
                        Object value = obj.get(key);
                        Logger.e("key " + key + " value " + value.toString());

                        multipart.addFormField("" + key, "" + value.toString());
                    } catch (JSONException e) {
                        // Something went wrong!
                        return null;
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


            /*
             if u have file add this parametr
             */
           // multipart.addFilePart("photo", file);


            List<String> response = multipart.finish();

            System.out.println("SERVER REPLIED:");
            StringBuilder sb = new StringBuilder();
            if (response == null) {
                return null;
            }
            for (String line : response) {
                System.out.println(line);
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException ex) {
            System.err.println(ex);
        }
        return null;
    }

    public class MultipartUtility {

        public MultipartUtility(String requestURL, String ch)
                throws IOException {
            charset = ch;
            boundary = "===" + System.currentTimeMillis() + "===";

            URL url = new URL(requestURL);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setUseCaches(false);
            httpConn.setRequestMethod("POST");
            httpConn.setDoOutput(true); // indicates POST method
            httpConn.setDoInput(true);

            //if need autorization 
            //httpConn.setRequestProperty("Authorization", "Basic " + encoded);

            httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            outputStream = httpConn.getOutputStream();
            writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
        }


        public void addFormField(String name, String value) {
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
                    .append(LINE_FEED);
            writer.append("Content-Type: text/plain; charset=" + charset).append(
                    LINE_FEED);
            writer.append(LINE_FEED);
            writer.append(value).append(LINE_FEED);
            writer.flush();
        }

        public void addFilePart(String fieldName, File uploadFile)
                throws IOException {
            String fileName = uploadFile.getName();
            writer.append("--" + boundary).append(LINE_FEED);
            writer.append(
                    "Content-Disposition: form-data; name=\"" + fieldName
                            + "\"; filename=\"" + fileName + "\"")
                    .append(LINE_FEED);
            writer.append(
                    "Content-Type: "
                            + URLConnection.guessContentTypeFromName(fileName))
                    .append(LINE_FEED);
            writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
            writer.append(LINE_FEED);
            writer.flush();

            FileInputStream inputStream = new FileInputStream(uploadFile);
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
            inputStream.close();

            writer.append(LINE_FEED);
            writer.flush();
        }

        public void addHeaderField(String name, String value) {
            writer.append(name + ": " + value).append(LINE_FEED);
            writer.flush();
        }


        public List<String> finish() throws IOException {
            List<String> response = new ArrayList<String>();

            writer.append(LINE_FEED).flush();
            writer.append("--" + boundary + "--").append(LINE_FEED);
            writer.close();

            int status = httpConn.getResponseCode();
            if (status == HttpURLConnection.HTTP_OK) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        httpConn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    response.add(line);
                }
                reader.close();
                httpConn.disconnect();
            } else {
                BufferedReader r = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
                StringBuilder total = new StringBuilder();
                String line;
                while ((line = r.readLine()) != null) {
                    total.append(line).append('\n');
                }
                Logger.e("Exception : " + total.toString());
                return null;
            }

            return response;
        }
    }
}

以及如何使用:

 FileUploader fileUploader = new FileUploader();
 String result = fileUploader.worker(url, params)

params - 将其jsonobject转换为字符串(mJsonObject.toString())

  

// multipart.addFilePart(“photo”,file);

服务器上的

photo = param(受欢迎的文件名/文件/照片/图像)