当前位置: 首页 > 面试题库 >

ANDROID java.net.URLConnection一次发送图像和数据

雍俊远
2023-03-14
问题内容

我使用java.net.URLConnection使用POST方法将图像和一些参数发送到服务器。我下面的代码可以很好地将图像发送到服务器,但是我有点困惑附加一些参数并一次发送到服务器。我一直在这里和这里,但我认为它与我的代码不同的方法。

这是下面的代码段:

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.widget.Toast;

import com.yai.app.support.DialogHandler;

public class ThreadImageUploader {
    private int serverResponseCode = 0;
    private ProgressDialog dialog;
    private Activity activity;

    public ThreadImageUploader(ProgressDialog mProgressDialog, Activity mActivity){
        dialog = mProgressDialog;
        activity = mActivity;
    }

    public int uploadFile(final String sourceFileUri, final String upLoadServerUri) {
        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {             
             dialog.dismiss();

             Log.e("uploadFile", "Source File not exist : " + sourceFileUri);

             activity.runOnUiThread(new Runnable() {
                 public void run() {
                     new DialogHandler().customDialog(activity, "ERROR", "Source File not exist : " + sourceFileUri);
                 }
             });

             return 0;

        }
        else{
             try { 
                 // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);

                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection(); 
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                 conn.setRequestProperty("uploaded_file", fileName);

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

                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
                                           + fileName + "'" + lineEnd);

                 dos.writeBytes(lineEnd);

                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available();

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

                 // read file and write it into form...
                 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);   
                  }

                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();

                 Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                 if(serverResponseCode == 200){
                     activity.runOnUiThread(new Runnable() {
                          public void run() {
                              String message = "File Upload Completed.";                               
                              Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
                          }
                      });                
                 }

                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();

            } catch (MalformedURLException ex) {
                dialog.dismiss();  
                ex.printStackTrace();

                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(activity, "MalformedURLException : : check script url.", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
            } catch (Exception e) {
                dialog.dismiss();  
                e.printStackTrace();

                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(activity, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
            }
            dialog.dismiss();       
            return serverResponseCode;

         }
       } 
}

我如何一次将图像和某些参数发送到服务器?非常感谢。


问题答案:

最后,这里是我的问题的解决方案。下面的代码段可用于上传图像并将文本发送到服务器。也许这篇文章可以帮助其他人:)

这是代码:

public int uploadFile(final String sourceFileUri, final String upLoadServerUri, final String renameFile) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(sourceFileUri);

        if (!sourceFile.isFile()) {             
             dialog.dismiss();

             Log.e("uploadFile", "Source File not exist : " + sourceFileUri);

             activity.runOnUiThread(new Runnable() {
                 public void run() {
                     new DialogHandler().customDialog(activity, "ERROR", "Source File not exist : " + sourceFileUri);
                 }
             });

             return 0;

        }
        else{
             try {               
                 // open a URL connection to the Servlet
                 FileInputStream fileInputStream = new FileInputStream(sourceFile);
                 URL url = new URL(upLoadServerUri);

                 // Open a HTTP  connection to  the URL
                 conn = (HttpURLConnection) url.openConnection(); 
                 conn.setDoInput(true); // Allow Inputs
                 conn.setDoOutput(true); // Allow Outputs
                 conn.setUseCaches(false); // Don't use a Cached Copy
                 conn.setRequestMethod("POST");
                 conn.setRequestProperty("Connection", "Keep-Alive");
                 conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                 conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                 conn.setRequestProperty("uploaded_file", renameFile);

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

                 // add parameters
                 dos.writeBytes(twoHyphens + boundary + lineEnd);
                 dos.writeBytes("Content-Disposition: form-data; name=\"type\""
                         + lineEnd);
                 dos.writeBytes(lineEnd);

                 // assign value
                 dos.writeBytes("Your value");
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + lineEnd);

                 // send image
                 dos.writeBytes(twoHyphens + boundary + lineEnd); 
                 dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
                         + renameFile + "'" + lineEnd);

                 dos.writeBytes(lineEnd);

                 // create a buffer of  maximum size
                 bytesAvailable = fileInputStream.available();

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

                 // read file and write it into form...
                 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);   
                  }

                 // send multipart form data necesssary after file data...
                 dos.writeBytes(lineEnd);
                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                 // Responses from the server (code and message)
                 serverResponseCode = conn.getResponseCode();
                 String serverResponseMessage = conn.getResponseMessage();

                 Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

                 if(serverResponseCode == 200){
                     activity.runOnUiThread(new Runnable() {
                          public void run() {
                              String message = "File Upload Completed.";                               
                              Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
                          }
                      });                
                 }

                 //close the streams //
                 fileInputStream.close();
                 dos.flush();
                 dos.close();

            } catch (MalformedURLException ex) {
                dialog.dismiss();  
                ex.printStackTrace();

                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(activity, "MalformedURLException : : check script url.", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
            } catch (Exception e) {
                dialog.dismiss();  
                e.printStackTrace();

                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(activity, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show();
                    }
                });

                Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
            }
            dialog.dismiss();       
            return serverResponseCode;

         }
       }


 类似资料:
  • 为空。对如何发送图像有什么建议吗? 谢了。

  • 我正在尝试使用MultipartEntityBuilder和HttpURLConnection向服务器发送一个映像,然后接收一个字符串答案(现在它使用http协议,但我将使用此代码或非常类似的代码使用https来完成)。但当我按下按钮发送时,应用程序崩溃了,而logcat没有告诉我任何关于捕获的信息。下一个代码来自我执行此操作的类: 我试图解决这个问题:从浏览器下载包,然后将其粘贴到库中的文件夹/

  • 我正在使用将参数和图像发送到服务器。 在服务器端,数据将是一个字典,由参数(QueryDict)和图像数据(MultiValueDict)合并而成: 我认为'MultiValueDict'是来自这部分代码: 然而,我希望有这样的多值dict:{code>{u'groupImages':[{u'image':[ 数据格式是具有数组值的字典,数组具有另一个字典值。 那么我该怎么做才能使

  • 我正在开发一个基于Firebase的聊天演示应用程序的Android应用程序。我面临的问题是,当我想传输图像时,我不知道如何处理这种情况。发送图像时,我在Base64中编码,并将其作为字符串发送。那么这里对图像的解码过程又会是怎样的呢?

  • 问题内容: 我只想指出:我的互联网连接糟透了。因此,我开始推送新图像,情况如下所示: 同时推入所有这些层都只是在扼杀我的互联网连接,不允许我进行导航和码头工人抵制,因为其中许多层上载有错误,并一次又一次地重新启动。 有没有办法一次上传单个图层?(顺便说一句,不,请不要更改我的ISP或我的路由器) 问题答案: 在我的Ubuntu中,我添加了: 然后。像魅力一样工作。

  • 我试图做简单的超文本传输协议后请求使用以下代码:Golang代码从另一个SO后 它发送了两次http请求(我尝试了向自己的web服务和Firebase消息服务器发送)。有人知道怎么回事吗?非常感谢。 编辑忽略我,找出是AVG反病毒造成的问题。如果我这样做:然后按enter键一次,AVG会中断,说它已经扫描了它,然后让它运行。这会导致http调用两次。如果我在运行前禁用了防病毒软件,那么http请求