簡體   English   中英

將InputStream作為參數傳遞給Web服務

[英]passing InputStream as parameter to web service

我正在嘗試上傳文件,但我沒有通過html表單進行上傳。 不能使用QueryParam和PathParam。 因此,任何人都可以告訴如何通過流。

我的HttPClient看起來像:

try
    {
        HttpClient httpclient = new DefaultHttpClient();
        InputStream stream=new FileInputStream(new File("C:/localstore/ankita/Desert.jpg"));
        String url="http://localhost:8080/Cloud/webresources/fileupload";
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
    }
    catch(Exception e){}

和我的Web服務類看起來像:

@Path("/fileupload")
public class UploadFileService {

@POST
@Consumes(MediaType.APPLICATION_OCTET_STREAM)

public Response uploadFile(InputStream in) throws IOException
{     
    String uploadedFileLocation = "c://filestore/Desert.jpg" ;

    // save it
    saveToFile(in, uploadedFileLocation);

    String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation;

    return Response.status(200).entity(output).build();

}

// save uploaded file to new location
private void saveToFile(InputStream uploadedInputStream,String uploadedFileLocation) 
{
    try {
        OutputStream out = null;
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) 
        {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) 
    {
        e.printStackTrace();
    }

}

}

誰能幫忙?

 String url="http://localhost:8080/Cloud/webresources/fileupload";
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(new File("C:/localstore/ankita/Desert.jpg")), -1);
        reqEntity.setContentType("binary/octet-stream");
        reqEntity.setChunked(true); // Send in multiple parts if needed
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);   

Web服務的外觀如何?

你不能那樣做。 您無法在HTTP請求中傳遞流,因為流不可序列化。

這樣做的方法是創建一個HttpEntity來包裝流(例如InputStreamEntity ),然后使用setEntity將其附加到HttpPOST對象。 然后發送POST,客戶端將從您的流中讀取並發送字節作為請求的“ POST數據”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM