douxi3085 2010-07-10 23:52
浏览 23
已采纳

在Web服务器问题上POST图像

I'm trying to post a jpg image to a web server. I've tested my PHP script at the server and I'm being able to upload an image using a form. Now I'm trying to make a Blackberry application to POST the image to the server using the same script however when I test the Java code, PHP tells me that NOTHING was POSTed, I'm not sure what I'm doing wrong but I'm doing something like this:

String mBoundary = "SUPSUPSUPSUP";

/* Preparar objeto a enviar */

InputStream mImagen = this.getClass().getResourceAsStream("sample.jpg");            
byte[] mBytesPostear = IOUtilities.streamToBytes(mImagen);

HttpConnection mConexion = (HttpConnection) Connector.open("http://www.raspberry.com/script.php");                      

/* Preparar headers del POST. Es multiformulario con POST de un archivo */
mConexion.setRequestMethod(HttpConnection.POST);
mConexion.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + ";boundary=" + mBoundary);
mConexion.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(mBytesPostear.length));
mConexion.setRequestProperty( "x-rim-transcode-content", "none" );                      

/* Preparar contenido de salida */
ByteArrayOutputStream mOutput = new ByteArrayOutputStream();            
OutputStream mOS = mConexion.openOutputStream();

/* Escribir contenido */
String nuevaLinea = "
";
String contDisp="Content-Disposition:form-data; name=\"foto\";filename=\"sample.jpg\"";
String contEnc = "Content-Transfer-Encoding: binary";
String type="Content-Type:image/jpeg";

mOutput.write(nuevaLinea.getBytes());
mOutput.write("--".getBytes());
mOutput.write(mBoundary.getBytes());
mOutput.write(nuevaLinea.getBytes());
mOutput.write(contDisp.getBytes());
mOutput.write(nuevaLinea.getBytes());
mOutput.write(type.getBytes());
mOutput.write(nuevaLinea.getBytes());
mOutput.write(contEnc.getBytes());
mOutput.write(nuevaLinea.getBytes());
mOutput.write(nuevaLinea.getBytes());
mOutput.write(mBytesPostear);
mOutput.write(nuevaLinea.getBytes());
mOutput.write("--".getBytes());
mOutput.write(mBoundary.getBytes());
mOutput.write("--".getBytes());         
mOutput.write(nuevaLinea.getBytes());

/**********************/

/* Escribir el contenido */
mOS.write(mOutput.toByteArray());

mOutput.flush();
mOutput.close();

mOS.flush();
mOS.close();

/* Recibir respuesta del servidor */
InputStream mIS = mConexion.openInputStream();
int mLongitud = (int) mConexion.getLength();

if (mLongitud > 0) {                

    int mActual = 0;
    int mBytesLeidos = 0;
    byte[] mBytes = new byte[mLongitud];

    while ((mBytesLeidos != mLongitud) && (mActual != -1)){
        mActual = mIS.read(mBytes, mBytesLeidos, mLongitud - mBytesLeidos);
        mBytesLeidos += mActual;
    }               

    String mRespuesta = new String(mBytes);     
    System.out.println("Respuesta: " + mRespuesta);

} 

I just tried to clone the header that is sent by Chrome when I use the form, I think they have the same information.

My PHP script first checks if something was posted, if nothing was posted, then it returns a message so I'm able to "consume" the script in the web server and I can see that the Blackberry device is uploading the data but the answer is that nothing was posted.

I think I'm sending the info to the server in a wrong format.

Any help would be greatly appreciated.

Thanks!

  • 写回答

2条回答 默认 最新

  • duanfengtuo6012 2010-07-16 13:45
    关注

    I added to the code the complete length and checked my PHP script and it's working fine now: this is the complete snippet just in case someone else needs it:

    public class PostImagen {
    private String mURL;
    private byte[] mDatos;
    
    public PostImagen(String URLServicio, byte[] Datos){
        mDatos = Datos;
        mURL = URLServicio;
    }
    
    public void getRespuesta() throws Exception {       
        try {                                      
            String mBoundary = "SUPSUP";            
    
            /* Strings a usar para el contenido */
            String nuevaLinea = "
    ";
            String contDisp="Content-Disposition: multipart/form-data; name=\"foto\";filename=\"sample.jpg\"";
            String contEnc = "Content-Transfer-Encoding: binary";
            String type="Content-Type:image/jpeg";
    
            /* Preparar objeto a enviar */
            byte[] mBytesPostear;
            if (mDatos == null){
                InputStream mImagen = this.getClass().getResourceAsStream("sample.jpg");            
                mBytesPostear = IOUtilities.streamToBytes(mImagen);
            } else {
                mBytesPostear = mDatos;
            }                       
    
            System.err.println("Longitud de imagen: " + mBytesPostear.length);
    
    
    
            /* Preparar contenido de salida */
            ByteArrayOutputStream mOutput = new ByteArrayOutputStream();
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write("--".getBytes());
            mOutput.write(mBoundary.getBytes());
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write(contDisp.getBytes());
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write(type.getBytes());
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write(contEnc.getBytes());
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write(mBytesPostear);
            mOutput.write(nuevaLinea.getBytes());
            mOutput.write("--".getBytes());
            mOutput.write(mBoundary.getBytes());
            mOutput.write("--".getBytes());         
            mOutput.write(nuevaLinea.getBytes());
    
            /* Preparar conexión y headers */
            HttpConnection mConexion = (HttpConnection) Connector.open(mURL);
            mConexion.setRequestMethod(HttpConnection.POST);
            mConexion.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE, HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA + ";boundary=" + mBoundary);
            mConexion.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(mOutput.size()));          
            mConexion.setRequestProperty( "x-rim-transcode-content", "none" );      
    
            /**********************/
            System.err.println("Escribiendo stream");
    
            OutputStream mOS = mConexion.openOutputStream();            
    
            /* Escribir el contenido */
            mOS.write(mOutput.toByteArray());
    
            mOutput.flush();
            mOutput.close();
    
            mOS.flush();
            mOS.close();
    
            System.err.println("Se terminó de escribir payload, recibiendo respuesta");
    
            /* Recibir respuesta del servidor */
            if (mConexion.getResponseCode() != HttpConnection.HTTP_OK){             
                throw new Exception("El servidor NO regresó OK (200) al leer la respuesta. Saliendo...");
            }
    
            InputStream mIS = mConexion.openInputStream();
            int mLongitud = (int) mConexion.getLength();
    
            if (mLongitud > 0) {                
    
                int mActual = 0;
                int mBytesLeidos = 0;
                byte[] mBytes = new byte[mLongitud];
    
                while ((mBytesLeidos != mLongitud) && (mActual != -1)){
                    mActual = mIS.read(mBytes, mBytesLeidos, mLongitud - mBytesLeidos);
                    mBytesLeidos += mActual;
                }               
    
                String mRespuesta = new String(mBytes);     
                System.out.println("Respuesta: " + mRespuesta);
    
            } else {                                            
                throw new Exception("No se recibió respuesta del servidor");
            }                                           
        } catch (IOException e) {                                   
            throw new Exception("Error de lectura o escritura: " + e.getMessage());
        }       
    }
    

    }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器