使用 https 和凭据进行 android 文件上传

发布于 2024-10-02 23:17:23 字数 4347 浏览 2 评论 0原文

我尝试发出一个帖子请求,其中包含一个文件,问题是,我必须使用 ssl 和 BasicCredentialprovider。以下代码适用于正常的 POST 请求: (url 是 url,nvps 是 nameValuePair)

    DefaultHttpClient http = new DefaultHttpClient();
    SSLSocketFactory ssl =  (SSLSocketFactory)http.getConnectionManager().getSchemeRegistry().getScheme( "https" ).getSocketFactory(); 
    ssl.setHostnameVerifier( SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER );
    final String username = "xxx";
    final String password = "xxx";
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
    BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
    cP.setCredentials(AuthScope.ANY, c); 
    http.setCredentialsProvider(cP);
    HttpResponse res;
    try {
        HttpPost httpost = new HttpPost(url);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));

        res = http.execute(httpost);


        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        res = null;
        httpost = null;
        return  new String(baf.toByteArray());
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 

我找到了以下代码来执行文件上传,该代码有效,但我无法将上传与身份验证结合起来,让他忽略 ssl 错误(证书不是有效)

String BOUNDRY = "==================================";
final String username = "xxx";
final String password = "xxx";
HttpURLConnection conn = null;
try {
     String contentDisposition = "Content-Disposition: form-data; name=\"userfile\";         filename=\"" + file.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";
            // This is the standard format for a multipart request
            StringBuffer requestBody = new StringBuffer();
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append('\n');
            requestBody.append(contentDisposition);
            requestBody.append('\n');
            requestBody.append(contentType);
            requestBody.append('\n');
            requestBody.append('\n');

            requestBody.append(new String(getBytesFromFile(file)));
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append("--");

            // Make a connect to the server
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // Put the authentication details in the request
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

            // Send the body
            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            dataOS.writeBytes(requestBody.toString());
            dataOS.flush();
            dataOS.close();

            // Ensure we got the HTTP 200 response code
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
            }

            // Read the response
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int bytesRead;
            while((bytesRead = is.read(bytes)) != -1) {
                baos.write(bytes, 0, bytesRead);
            }
            byte[] bytesReceived = baos.toByteArray();
            baos.close();

            is.close();
            String response = new String(bytesReceived);
            ret = response;
            // TODO: Do something here to handle the 'response' string

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

有什么建议吗?

i try to make a post request, witch contains a file, the problem is, i have to use ssl and the BasicCredentialprovider. The following code works for me with normal POST requests:
(url is the url, nvps is the nameValuePair)

    DefaultHttpClient http = new DefaultHttpClient();
    SSLSocketFactory ssl =  (SSLSocketFactory)http.getConnectionManager().getSchemeRegistry().getScheme( "https" ).getSocketFactory(); 
    ssl.setHostnameVerifier( SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER );
    final String username = "xxx";
    final String password = "xxx";
    UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
    BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
    cP.setCredentials(AuthScope.ANY, c); 
    http.setCredentialsProvider(cP);
    HttpResponse res;
    try {
        HttpPost httpost = new HttpPost(url);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.DEFAULT_CONTENT_CHARSET));

        res = http.execute(httpost);


        InputStream is = res.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while((current = bis.read()) != -1){
              baf.append((byte)current);
         }
        res = null;
        httpost = null;
        return  new String(baf.toByteArray());
       } 
    catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 
    catch (IOException e) {
        // TODO Auto-generated catch block
        return e.getMessage();
    } 

I found the following code to perform a Fileupload, the code works, but i'm not able to combine the Upload with the autenthification an let him ignore the ssl errors (the cetificate is not valid)

String BOUNDRY = "==================================";
final String username = "xxx";
final String password = "xxx";
HttpURLConnection conn = null;
try {
     String contentDisposition = "Content-Disposition: form-data; name=\"userfile\";         filename=\"" + file.getName() + "\"";
            String contentType = "Content-Type: application/octet-stream";
            // This is the standard format for a multipart request
            StringBuffer requestBody = new StringBuffer();
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append('\n');
            requestBody.append(contentDisposition);
            requestBody.append('\n');
            requestBody.append(contentType);
            requestBody.append('\n');
            requestBody.append('\n');

            requestBody.append(new String(getBytesFromFile(file)));
            requestBody.append("--");
            requestBody.append(BOUNDRY);
            requestBody.append("--");

            // Make a connect to the server
            URL url = new URL(targetURL);
            conn = (HttpURLConnection) url.openConnection();

            // Put the authentication details in the request
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDRY);

            // Send the body
            DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
            dataOS.writeBytes(requestBody.toString());
            dataOS.flush();
            dataOS.close();

            // Ensure we got the HTTP 200 response code
            int responseCode = conn.getResponseCode();
            if (responseCode != 200) {
                throw new Exception(String.format("Received the response code %d from the URL %s", responseCode, url));
            }

            // Read the response
            InputStream is = conn.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int bytesRead;
            while((bytesRead = is.read(bytes)) != -1) {
                baos.write(bytes, 0, bytesRead);
            }
            byte[] bytesReceived = baos.toByteArray();
            baos.close();

            is.close();
            String response = new String(bytesReceived);
            ret = response;
            // TODO: Do something here to handle the 'response' string

        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱本泡沫多脆弱 2024-10-09 23:17:23

通过添加 appache-mime4j-0.6.jar 和 httpmime-4.0.3.jar 以及以下代码来解决:

public static boolean upload_image(String url, List<NameValuePair> nameValuePairs,String encoding) {

        DefaultHttpClient http = new DefaultHttpClient();
        SSLSocketFactory ssl =  (SSLSocketFactory)http.getConnectionManager().getSchemeRegistry().getScheme( "https" ).getSocketFactory(); 
        ssl.setHostnameVerifier( SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER );
        final String username = "xxx";
        final String password = "xxx";
        UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
        BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
        cP.setCredentials(AuthScope.ANY, c); 
        http.setCredentialsProvider(cP);
        HttpResponse res;
        try {
            HttpPost httpost = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); 

            for(int index=0; index < nameValuePairs.size(); index++) { 
                ContentBody cb;
                if(nameValuePairs.get(index).getName().equalsIgnoreCase("File")) { 
                    File file = new File(nameValuePairs.get(index).getValue());
                    FileBody isb = new FileBody(file,"application/*");

                    /*
                    byte[] data = new byte[(int) file.length()];
                    FileInputStream fis = new FileInputStream(file);
                    fis.read(data);
                    fis.close();

                    ByteArrayBody bab = new ByteArrayBody(data,"application/*","File");
                    entity.addPart(nameValuePairs.get(index).getName(), bab);
                    */  
                    entity.addPart(nameValuePairs.get(index).getName(), isb);
                } else { 
                    // Normal string data 
                    cb =  new StringBody(nameValuePairs.get(index).getValue(),"", null);
                    entity.addPart(nameValuePairs.get(index).getName(),cb); 
                } 
            } 


            httpost.setEntity(entity);
            res = http.execute(httpost);

            InputStream is = res.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while((current = bis.read()) != -1){
                  baf.append((byte)current);
             }
            res = null;
            httpost = null;
            String ret = new String(baf.toByteArray(),encoding);
            GlobalVars.LastError = ret;
            return  true;
           } 
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            return true;
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            return true;
        } 
}

solved by adding the appache-mime4j-0.6.jar and httpmime-4.0.3.jar and the following code:

public static boolean upload_image(String url, List<NameValuePair> nameValuePairs,String encoding) {

        DefaultHttpClient http = new DefaultHttpClient();
        SSLSocketFactory ssl =  (SSLSocketFactory)http.getConnectionManager().getSchemeRegistry().getScheme( "https" ).getSocketFactory(); 
        ssl.setHostnameVerifier( SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER );
        final String username = "xxx";
        final String password = "xxx";
        UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
        BasicCredentialsProvider cP = new BasicCredentialsProvider(); 
        cP.setCredentials(AuthScope.ANY, c); 
        http.setCredentialsProvider(cP);
        HttpResponse res;
        try {
            HttpPost httpost = new HttpPost(url);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT); 

            for(int index=0; index < nameValuePairs.size(); index++) { 
                ContentBody cb;
                if(nameValuePairs.get(index).getName().equalsIgnoreCase("File")) { 
                    File file = new File(nameValuePairs.get(index).getValue());
                    FileBody isb = new FileBody(file,"application/*");

                    /*
                    byte[] data = new byte[(int) file.length()];
                    FileInputStream fis = new FileInputStream(file);
                    fis.read(data);
                    fis.close();

                    ByteArrayBody bab = new ByteArrayBody(data,"application/*","File");
                    entity.addPart(nameValuePairs.get(index).getName(), bab);
                    */  
                    entity.addPart(nameValuePairs.get(index).getName(), isb);
                } else { 
                    // Normal string data 
                    cb =  new StringBody(nameValuePairs.get(index).getValue(),"", null);
                    entity.addPart(nameValuePairs.get(index).getName(),cb); 
                } 
            } 


            httpost.setEntity(entity);
            res = http.execute(httpost);

            InputStream is = res.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while((current = bis.read()) != -1){
                  baf.append((byte)current);
             }
            res = null;
            httpost = null;
            String ret = new String(baf.toByteArray(),encoding);
            GlobalVars.LastError = ret;
            return  true;
           } 
        catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            return true;
        } 
        catch (IOException e) {
            // TODO Auto-generated catch block
            return true;
        } 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文