将映像文件发布到RESTful Web服务

时间:2010-09-14 02:06:49

标签: asp.net-mvc blackberry

我正在尝试将图像文件发送到网络服务。

这是我的代码:

   ConnectionFactory connFact = new ConnectionFactory();
        ConnectionDescriptor connDesc;

        //String value = new String(data);
        String value= Base64OutputStream.encodeAsString(data, 0, data.length, false, false);

        value = "imgData=" + value;

        connDesc = connFact.getConnection("http://localhost:50806/Send");
        int iResponseCode = 0;
        HttpConnection httpConn = null;
        OutputStream os = null;
        if (connDesc != null)
        {

            try
            {
             byte[] theByteArray = value.getBytes();

                httpConn = (HttpConnection)connDesc.getConnection();

                httpConn.setRequestProperty("Content-Type", "image/jpeg");
                httpConn.setRequestMethod(HttpConnection.POST);
                httpConn.setRequestProperty("Content-Disposition", "form-data");
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("Content-Length", String.valueOf(data.length));

                //os = httpConn.openOutputStream();
                //os.write(theByteArray);
                DataOutputStream printout = new DataOutputStream (httpConn.openOutputStream()); 
                printout.write(theByteArray);
                iResponseCode = httpConn.getResponseCode();        
             } 
            catch(Exception e){
                e.printStackTrace();
            }
            finally{
                if(os != null)
                    os.close();

                if(httpConn != null){                    
                 httpConn.close();
                }
            }

        }
  return Integer.toString(iResponseCode);  

表示图像文件的字节数组传递给方法。

服务签名:

   [AcceptVerbs(HttpVerbs.Post)]  
    public ActionResult Send(string imgData)
    {}

有关如何发送此内容的任何想法?

非常感谢, 丹

1 个答案:

答案 0 :(得分:1)

Base64编码的字符串可能太大而无法作为GET请求中的URL参数传递。沿途的设备或某些代理可能会对请求做一些不好的事情。使用POST请求会更安全。为此,请将请求设置为带有httpConn.setRequestMethod(HttpConnection.POST)的POST,然后使用httpConn.openOutputStream()(可能还有PostData类)将所有表单参数写入请求正文中