android - 发送图像到服务器

标签 android

如何在没有名称-值对的情况下将图像发送到服务器?我知道这是基本问题,但在 stackoverflow 中对此没有明确的答案。我们如何使用 -POST- 方法? (如您所知,名称-值对已贬值)。

最佳答案

public String postPhotoUploadRequest(File imageFile) {
        URL url;
        String response = "";
        int responseCode = -1;
        try {
            url         = new URL("your url");

            HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
            conn.addRequestProperty("Content-Type", "binary/octet-stream");
            conn.setDoOutput(true);
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            conn.setRequestMethod("POST");

            DataOutputStream writer     = new DataOutputStream(conn.getOutputStream());
            Bitmap bmp = ImageUtils.filePathToBitmap(imageFile.getPath());
            if(bmp != null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 50, bos);
                InputStream input = new ByteArrayInputStream(bos.toByteArray());

                byte[] buffer = new byte[1024];
                for (int length = 0; (length = input.read(buffer)) > 0; ) {
                    writer.write(buffer, 0, length);
                }
                writer.flush();
                writer.close();
            }

            responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br   = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response            = "Response Code : " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

关于android - 发送图像到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35746395/

相关文章:

java - 我的回收站 View 未显示其拥有的所有项目,我该如何修复它?

java - 带有 Android 应用程序的 Golang 后端

android - 单击后退按钮时, Activity 组不会刷新 Activity

java - 使用 Microsoft Graph API 仅按标题搜索 OneDrive 文件

android - 无法使用 MFP 控制台向多个平台(ios 和 android)注册应用程序

android - 无法在安卓设备上试用我的应用

android - 使用 defStyleAttr 无法在当前主题中找到自定义 View 的样式

android - 如何从 Android 中的 fragment 访问 Activity 菜单项?

android - 如何让用户更改 'Accounts and sync' 中的帐户数据

android - 没有 jar 文件的外部库