Android- POST多部分表单数据 [英] Android- POST multipart form data

查看:220
本文介绍了Android- POST多部分表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用视频和数据,例如电子邮件和姓名发送多部分的形式。 以下是我的code和它不工作,也没有来自服务器的响应

 档案文件=新的文件(将videoPath);
    HttpClient的HttpClient的=新DefaultHttpClient();
    HttpPost httppost =新HttpPost(URL);

        尝试 {
            //添加数据
            名单<的NameValuePair> namevaluepairs中=新的ArrayList<的NameValuePair>(2);
            nameValuePairs.add(新BasicNameValuePair(姓名,LDGHT));
            nameValuePairs.add(新BasicNameValuePair(电子邮件,hhh@example.com));

            httppost.setEntity(新UrlEn codedFormEntity(namevaluepairs中));
            httppost.setEntity(新FileEntity(文件,视频/ MP4));

            //执行HTTP POST请求
            HTT presponse响应= httpclient.execute(httppost);

        }赶上(ClientProtocolException E){
            // TODO自动生成的catch块
        }赶上(IOException异常E){
            // TODO自动生成的catch块
        }
 

解决方案

检查我的职位发送Mutipart数据的发布的数据与多部分服务器 ..

另外,请查阅本作参考<一个href="http://vikaskanani.word$p$pss.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/">Link

 新Task_finder()执行()。
 

上传视频文件到服务器:

 公共类Task_finder扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {
    私人最终ProgressDialog对话框=新ProgressDialog(Facebook_Post_View.this);
    //这里可以使用UI线程
    在preExecute保护无效(){
        this.dialog.setMessage(载入中...);
        this.dialog.setCancelable(假);
        this.dialog.show();
    }
    @覆盖
    保护无效doInBackground(虚空......为arg0){
        // TODO自动生成方法存根
        HttpURLConnection的康恩= NULL;
        DataOutputStream类DOS = NULL;
        inStream中的DataInputStream = NULL;
        字符串existingFileName = FILE_PATH;
        字符串lineEnd =\ r \ N的;
        串twoHyphens = - ;
        字符串边界=*****;
        INT读取动作,方bytesAvailable,缓冲区大小;
        byte []的缓冲区;
        INT maxBufferSize = 1 * 1024 * 1024;
        字符串urlString =你的PHP链接,上传图片;
        尝试{
            // ------------------客户端请求
            的FileInputStream的FileInputStream =新的FileInputStream(新文件(existingFileName));
            //打开一个URL连接到这个Servlet
            网址URL =新的URL(urlString);
            //打开一个HTTP连接网址
            康恩=(HttpURLConnection类)url.openConnection();
            //允许输入
            conn.setDoInput(真正的);
            //允许输出
            conn.setDoOutput(真正的);
            //不要使用缓存副本。
            conn.setUseCaches(假);
            //使用POST方法。
            conn.setRequestMethod(POST);
            conn.setRequestProperty(连接,保持活动);
            conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
            DOS =新DataOutputStream类(conn.getOutputStream());
            dos.writeBytes(twoHyphens +边界+ lineEnd);

            dos.writeBytes(内容处置:表格数据;名称= \UploadedFile的\;文件名= \+ upload_file_name +\+ lineEnd); // uploaded_file_name是要上载的文件的名称
            dos.writeBytes(lineEnd);
            方bytesAvailable = fileInputStream.available();
            BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
            缓冲区=新的字节[BUFFERSIZE]
            读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
            而(读取动作大于0){
                dos.write(缓冲液,0,BUFFERSIZE);
                方bytesAvailable = fileInputStream.available();
                BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
                读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
            fileInputStream.close();
            dos.flush();
            dos.close();
        }
        赶上(MalformedURLException的前){
            Log.e(调试,错误:+ ex.getMessage(),前);
        }
        赶上(IOException异常IOE){
            Log.e(调试,错误:+ ioe.getMessage(),IOE);
        }
        // ------------------读取服务器响应
        尝试 {
            inStream中=新的DataInputStream(conn.getInputStream());
            字符串str;
            而((海峡= inStream.readLine())!= NULL){
                Log.e(调试,服务器响应+ STR);
                reponse_data =海峡;
            }
            inStream.close();
        }
        赶上(IOException异常ioex){
            Log.e(调试,错误:+ ioex.getMessage(),ioex);
        }
       返回null;
    }

    @覆盖
    保护无效onPostExecute(无效的结果){

        如果(this.dialog.isShowing()){
            this.dialog.dismiss();
        }
    }
}
 

I would like to send multipart form with video and data such as Email and name. The following is my code and it does not work ,there is no response from the server

File file =new File(VideoPath);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("Name", "LDGHT"));
            nameValuePairs.add(new BasicNameValuePair("Email", "hhh@example.com"));

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            httppost.setEntity(new FileEntity(file, "video/mp4"));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

解决方案

Check my Post for Sending Mutipart Data Post Data to Server with Multipart..

Also Check this for Reference Link

new Task_finder().execute();

Upload Video File to Server :

    public class Task_finder extends AsyncTask<Void, Void, Void> {
    private final ProgressDialog dialog = new ProgressDialog(Facebook_Post_View.this);
    // can use UI thread here
    protected void onPreExecute() {
        this.dialog.setMessage("Loading...");
        this.dialog.setCancelable(false);
        this.dialog.show();
    }
    @Override
    protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = file_path;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary =  "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1*1024*1024;
        String urlString = "YOUR PHP LINK FOR UPLOADING IMAGE";
        try{
            //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.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);
            dos = new DataOutputStream( conn.getOutputStream() );
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + upload_file_name + "\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
            dos.writeBytes(lineEnd);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            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);
            fileInputStream.close();
            dos.flush();
            dos.close();
        }
        catch (MalformedURLException ex){
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
        catch (IOException ioe){
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }
        //------------------ read the SERVER RESPONSE
        try {
            inStream = new DataInputStream ( conn.getInputStream() );
            String str;
            while (( str = inStream.readLine()) != null){
                Log.e("Debug","Server Response "+str);
                reponse_data=str;
            }
            inStream.close();
        }
        catch (IOException ioex){
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
       return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
    }
}

这篇关于Android- POST多部分表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆