Java 从android设备向使用REST编写的服务器上的webservice发送文件(图像)

Java 从android设备向使用REST编写的服务器上的webservice发送文件(图像),java,android,web-services,rest,Java,Android,Web Services,Rest,我想将安卓设备上的图像发送到运行在tomcat服务器上的web应用程序。请帮助我编写将图像发送到web服务器上运行的REST web服务的小代码。如果可能的话,请给我提供示例代码。我不知道该用什么方法。任何帮助都将不胜感激。提前谢谢 编辑:这个问题的答案如下 while(it.hasNext()){ File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirect

我想将安卓设备上的图像发送到运行在tomcat服务器上的web应用程序。请帮助我编写将图像发送到web服务器上运行的REST web服务的小代码。如果可能的话,请给我提供示例代码。我不知道该用什么方法。任何帮助都将不胜感激。提前谢谢

编辑:这个问题的答案如下

while(it.hasNext()){
             File file = new File((new StringBuilder()).append(Environment.getExternalStorageDirectory()).append(File.separator).append("jcms").append(File.separator).append("Customer_").append( customer.getId()).toString());
             File[] listOfFiles = file.listFiles(); 

             for(int i=0;i<listOfFiles.length;i++){
                 JSONObject message = new JSONObject();
                 File fil=listOfFiles[i];
                 FileInputStream imageInFile = new FileInputStream(fil);
                 byte imageData[] = new byte[(int)fil.length()];
                 imageInFile.read(imageData);
                 String imageDataString = encodeImage(imageData);



                 URL url=new URL(ClearCustomersContract.CLEAR_SERVER_URL);
                 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                 connection.setDoOutput(true);
                 connection.setRequestProperty("Content-Type", "application/json");
                 connection.setRequestMethod("POST");
                 connection.setConnectTimeout(5000);
                 connection.setReadTimeout(5000);
                 OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
                 out.write(imageDataString);
                 out.close();

                 BufferedReader in = new BufferedReader(new InputStreamReader(
                         connection.getInputStream()));
                 while (in.readLine() != null) {
                 }
                 in.close();    
             }
        }
这就是我们将字符串转换回图像的方法

字节[]imageByteArray=decodeImage(jsonObj.get(“imageData”).toString()


您可以使用下面的代码使用RESTWebService上传图像

            try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(
                    "YOUR WEB SERVICE URL");
            entity = getMultipleEntityUpload();
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost,
                    httpContext);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();

            String line = "";
            StringBuilder total = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(
            is));

        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        String result =total.toString();

        } catch (Exception e) {
            // TODO: handle exception
        }

    private MultipartEntity getMultipleEntityUpload() {
    MultipartEntity entity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //imagePic is bitmap of your image      
        imagePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] arrByteImage = stream.toByteArray();
            try {
            entity.addPart(WS_Key_Constant.KEY_IMAGE, new ByteArrayBody(
                    arrByteImage, ".jpg"));
        } catch (Exception e) {
        }

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return entity;
}
检查一下。它给出了如何将文件上传到服务器的完整示例

或者检查下面的代码-

public class HttpFileUpload implements Runnable{
    URL connectURL;
    String responseString;
    String Title;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;

    HttpFileUpload(String urlString, String vTitle, String vDesc){
            try{
                    connectURL = new URL(urlString);
                    Title= vTitle;
                    Description = vDesc;
            }catch(Exception ex){
                Log.i("HttpFileUpload","URL Malformatted");
            }
    }

    void Send_Now(FileInputStream fStream){
            fileInputStream = fStream;
            Sending();
    }

    void Sending(){
            String iFileName = "ovicam_temp_vid.mp4";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            String Tag="fSnd";
            try
            {
                    Log.e(Tag,"Starting Http File Sending to URL");

                    // Open a HTTP connection to the URL
                    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                    // Allow Inputs
                    conn.setDoInput(true);

                    // Allow Outputs
                    conn.setDoOutput(true);

                    // Don't use a cached copy.
                    conn.setUseCaches(false);

                    // Use a post method.
                    conn.setRequestMethod("POST");

                    conn.setRequestProperty("Connection", "Keep-Alive");

                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Title);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Description);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                    dos.writeBytes(lineEnd);

                    Log.e(Tag,"Headers are written");

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

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

                    // read file and write it into form...
                    int 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);
                    }
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    // close streams
                    fileInputStream.close();

                    dos.flush();

                    Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                    InputStream is = conn.getInputStream();

                    // retrieve the response from server
                    int ch;

                    StringBuffer b =new StringBuffer();
                    while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                    String s=b.toString();
                    Log.i("Response",s);
                    dos.close();
            }
            catch (MalformedURLException ex)
            {
                    Log.e(Tag, "URL error: " + ex.getMessage(), ex);
            }

            catch (IOException ioe)
            {
                    Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
            }
    }

    @Override
    public void run() {
            // TODO Auto-generated method stub
    }
  }

public void UploadFile(){
  try {
  // Set your file path here
  FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");

 // Set your server page url (and the file title/description)
 HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");

 hfu.Send_Now(fstrm);

  } catch (FileNotFoundException e) {
    // Error: File not found
 }
 }

嗨,拉维,谢谢你的回复。另外,你能给我一个在服务器端接受此流的Web服务的模板吗?对不起,伙计,我没有那么多关于Web服务的知识可以分享。嗨,Y.S.谢谢你的回复。您可以在服务器端发布webservice模板以接受此请求吗。
            try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext httpContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(
                    "YOUR WEB SERVICE URL");
            entity = getMultipleEntityUpload();
            httpPost.setEntity(entity);
            HttpResponse httpResponse = httpClient.execute(httpPost,
                    httpContext);
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream is = httpEntity.getContent();

            String line = "";
            StringBuilder total = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(
            is));

        while ((line = rd.readLine()) != null) {
            total.append(line);
        }
        String result =total.toString();

        } catch (Exception e) {
            // TODO: handle exception
        }

    private MultipartEntity getMultipleEntityUpload() {
    MultipartEntity entity = new MultipartEntity(
            HttpMultipartMode.BROWSER_COMPATIBLE);
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        //imagePic is bitmap of your image      
        imagePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        byte[] arrByteImage = stream.toByteArray();
            try {
            entity.addPart(WS_Key_Constant.KEY_IMAGE, new ByteArrayBody(
                    arrByteImage, ".jpg"));
        } catch (Exception e) {
        }

    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return entity;
}
public class HttpFileUpload implements Runnable{
    URL connectURL;
    String responseString;
    String Title;
    String Description;
    byte[ ] dataToServer;
    FileInputStream fileInputStream = null;

    HttpFileUpload(String urlString, String vTitle, String vDesc){
            try{
                    connectURL = new URL(urlString);
                    Title= vTitle;
                    Description = vDesc;
            }catch(Exception ex){
                Log.i("HttpFileUpload","URL Malformatted");
            }
    }

    void Send_Now(FileInputStream fStream){
            fileInputStream = fStream;
            Sending();
    }

    void Sending(){
            String iFileName = "ovicam_temp_vid.mp4";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";
            String Tag="fSnd";
            try
            {
                    Log.e(Tag,"Starting Http File Sending to URL");

                    // Open a HTTP connection to the URL
                    HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();

                    // Allow Inputs
                    conn.setDoInput(true);

                    // Allow Outputs
                    conn.setDoOutput(true);

                    // Don't use a cached copy.
                    conn.setUseCaches(false);

                    // Use a post method.
                    conn.setRequestMethod("POST");

                    conn.setRequestProperty("Connection", "Keep-Alive");

                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Title);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(Description);
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + lineEnd);

                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                    dos.writeBytes(lineEnd);

                    Log.e(Tag,"Headers are written");

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

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

                    // read file and write it into form...
                    int 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);
                    }
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    // close streams
                    fileInputStream.close();

                    dos.flush();

                    Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));

                    InputStream is = conn.getInputStream();

                    // retrieve the response from server
                    int ch;

                    StringBuffer b =new StringBuffer();
                    while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                    String s=b.toString();
                    Log.i("Response",s);
                    dos.close();
            }
            catch (MalformedURLException ex)
            {
                    Log.e(Tag, "URL error: " + ex.getMessage(), ex);
            }

            catch (IOException ioe)
            {
                    Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
            }
    }

    @Override
    public void run() {
            // TODO Auto-generated method stub
    }
  }

public void UploadFile(){
  try {
  // Set your file path here
  FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");

 // Set your server page url (and the file title/description)
 HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");

 hfu.Send_Now(fstrm);

  } catch (FileNotFoundException e) {
    // Error: File not found
 }
 }