【问题标题】:Upload base64 encoded image using HttPost and HttpClient使用 HttPost 和 HttpClient 上传 base64 编码的图像
【发布时间】:2014-10-16 12:28:38
【问题描述】:

我尝试将图像(base64 编码)连同其他值一起上传到 PHP 网络服务器,它会获取这些信息并进行一些进一步的处理。

以下函数是执行请求的 AsyncTask 的一部分。

我通过手动连接不同的值来构建 postData。

JsonUrlLook 类帮助我找到发送数据的正确 URL。我验证过了。没错。

当我尝试执行创建的 HttpPost 时,我的响应为空。有人知道这是为什么吗?

private String getPostData(String arrayString, String base64Image, String boundary) {
    String remoteMethod = "uploadPic";
    String postData = "";

    // Add remote method name
    postData += "--" + boundary + "\r\n";
    postData += "Content-Disposition: form-data; name=\"" + boundary + "[method]\"\r\n\r\n";
    postData += remoteMethod;

    postData += "--" + boundary + "\r\n";
    postData += "Content-Disposition: form-data; name=\"" + boundary + "[params]\"\r\n\r\n";
    postData += arrayString;

    postData += "--" + boundary + "\r\n";
    postData += "Content-Disposition: form-data; name=\"" + boundary + "\"\r\n\r\n";
    postData += "filename=\"image.jpg\"\r\n\r\n";
    postData += base64Image;

    postData += "--" + boundary + "--";

    return postData;
}

private String uploadPicture(String arrayString, String base64Image) {

    String boundary = "tx_fpoemobile_pi2";

    // Get post data
    String postData = getPostData(arrayString, base64Image, boundary);

    // Get webservice uri
    JsonUrlLookup lookup = new JsonUrlLookup(context);
    URL webserviceUrl = lookup.buildUrl(context.getResources().getString(R.string.page_uid_webservice));
    URI webserviceUri = null;
    try {
        webserviceUri = new URI(webserviceUrl.toString());
    } catch(Exception e) {
        // TODO
    }

    // Build client and post
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(webserviceUri);

    // Set header of post
    httpPost.setHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpPost.setHeader("Content-Length", String.valueOf(postData.length()));

    // Set body
    try {
        httpPost.setEntity(new StringEntity(postData));
    } catch (Exception e) {
        // TODO
    }

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpPost);
    } catch (ClientProtocolException e) {
        // TODO
    } catch (IOException e) {
        // TODO
    }

    return "uploadPictureSuccess";
}   

【问题讨论】:

    标签: android image http-post multipart


    【解决方案1】:

    你必须这样工作

    public void connectForMultipart() throws Exception {
        con = (HttpURLConnection) ( new URL(url)).openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        con.connect();
        os = con.getOutputStream();
    }
    
    public void addFormPart(String paramName, String value) throws Exception {
        writeParamData(paramName, value);
    }
    
    public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
        os.write( (delimiter + boundary + "\r\n").getBytes());
        os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\"; filename=\"" + fileName + "\"\r\n"  ).getBytes());
        os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
        os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
        os.write("\r\n".getBytes());
    
        os.write(data);
        
        os.write("\r\n".getBytes());
    }   
    public void finishMultipart() throws Exception {
        os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
    }
    

    获取响应

    httpPost.setEntity(entity);
    HttpResponse response = httpClient.execute(httpPost);
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    
    
    
    String sResponse;
    while ((sResponse = reader.readLine()) != null) 
     {
         s = s.append(sResponse);
     }
    
     if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
     {
         return s.toString();
     }else
     {
         return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
     }   
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    你可以发送任何东西来代替图片。

    在这种情况下,您需要httpmime-4.2.1-1.jar

    【讨论】:

    • 我说过我需要将图像作为 base64 编码字符串而不是二进制传输。但无论如何,我会尝试你的解决方案。
    • 您介意解释一下函数“writeParamData”吗?
    • 在您的帖子“获取响应”中,您使用 httpClient 和带有集合实体的 httpPost。这与第一部分有很大不同。它们是否连接,或者这些完全不同的方法。我不明白。
    • 和你的代码差不多..我只是为了更好的理解把它们分开了
    • 方法“writeParamData”怎么样?我该怎么做?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-13
    • 2015-09-05
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多