MultipartEntityBuilder从Android的HttpURLConnection的发送数据 [英] MultipartEntityBuilder to send data from Android httpurlconnection

查看:477
本文介绍了MultipartEntityBuilder从Android的HttpURLConnection的发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变了HTTPClient去precated code,但我得到setEntity错误,因为它dapricated,我不知道如何PAAS MultipartEntityBuilder被新httpConnectionUrl。 我的老德precated code snippt

 尝试{
        HttpClient的客户端=新DefaultHttpClient();
        HttpPost后=新HttpPost(imagePostUrl);

        对于(字符串文件名:fileNameArrayList){

            档案文件=新的文件(文件名);
            //第一

            INT质量= GeneralUtil.getQualityOfImage(文件);

            ByteArrayOutputStream BOS =新ByteArrayOutputStream();

            如果(质量< = 25){//这意味着图像文件大小以MB为单位的,所以我们需要avoide出现内存不足的问题。

                BitmapFactory.Options选项=新BitmapFactory.Options();
                options.inJustDe codeBounds = FALSE;
                options.in preferredConfig = Bitmap.Config.RGB_565;
                options.inDither = TRUE;
                尝试 {
                    位= BitmapFactory.de codeFILE(file.getPath(),选件);
                }赶上(OutOfMemoryError异常E){
                    System.gc()的;
                    位= GeneralUtil.de codeFILE(文件);

                }

                bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                bitmap.recycle();
                位= NULL;

            } 其他 {

                尝试 {
                    位= BitmapFactory.de codeFILE(file.getPath());
                    bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                    bitmap.recycle();
                    位= NULL;
                }赶上(OutOfMemoryError异常E){
                    System.gc()的;

                    尝试 {
                        BitmapFactory.Options选项=新BitmapFactory.Options();
                        options.inJustDe codeBounds = FALSE;
                        options.in preferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = TRUE;

                        位= BitmapFactory.de codeFILE(file.getPath(),选件);
                        bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                        bitmap.recycle();
                        位= NULL;
                    }赶上(OutOfMemoryError异常前){

                        位= GeneralUtil.de codeFILE(文件);
                        bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                        bitmap.recycle();
                        位= NULL;
                        抛出新的异常();
                    }
                }
            }

            byte []的数据= bos.toByteArray();
            串的timeStamp = GeneralUtil.generateTimeStamp();
            ByteArrayBody斌=新ByteArrayBody(数据,myMobileNo +_+的userName +_+的timeStamp +.JPG);

            MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
            multiPartEntityBuilder.addPart(uploadedfile1,斌);
            multiPartEntityBuilder.addPart(inviteId,新StringBody(inviteIdArrayList.get(0)的ToString(),Charset.forName(UTF-8)));
            post.setEntity(multiPartEntityBuilder.build());
            HTT presponse HTT presponse = NULL;
            HTT presponse = client.execute(后);
            的InputStream的InputStream = NULL;
            的InputStream = HTT presponse.getEntity()的getContent()。
            如果(的InputStream!= NULL)
                result.add(convertInputStreamToString(InputStream中));
            其他
                result.add(没有工作!);
        }
 

我的新工作不code snippt

 尝试{
        HttpURLConnection的httpcon =(HttpURLConnection类)((新的URL(imagePostUrl).openConnection()));
        httpcon.setDoOutput(真正的);
        对于(字符串文件名:fileNameArrayList){
            档案文件=新的文件(文件名);
            INT质量= GeneralUtil.getQualityOfImage(文件);
            ByteArrayOutputStream BOS =新ByteArrayOutputStream();
            如果(质量< = 25){
                BitmapFactory.Options选项=新BitmapFactory.Options();
                options.inJustDe codeBounds = FALSE;
                options.in preferredConfig = Bitmap.Config.RGB_565;
                options.inDither = TRUE;
                尝试 {
                    位= BitmapFactory.de codeFILE(file.getPath(),选件);
                }赶上(OutOfMemoryError异常E){
                    System.gc()的;
                    位= GeneralUtil.de codeFILE(文件);

                }
                bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                bitmap.recycle();
                位= NULL;

            } 其他 {

                尝试 {
                    位= BitmapFactory.de codeFILE(file.getPath());
                    bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                    bitmap.recycle();
                    位= NULL;
                }赶上(OutOfMemoryError异常E){
                    System.gc()的;

                    尝试 {
                        BitmapFactory.Options选项=新BitmapFactory.Options();
                        options.inJustDe codeBounds = FALSE;
                        options.in preferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = TRUE;

                        位= BitmapFactory.de codeFILE(file.getPath(),选件);
                        bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                        bitmap.recycle();
                        位= NULL;
                    }赶上(OutOfMemoryError异常前){

                        位= GeneralUtil.de codeFILE(文件);
                        bitmap.com preSS(比较pressFormat.JPEG,质量,BOS);
                        bitmap.recycle();
                        位= NULL;
                        抛出新的异常();
                    }


                }
            }
            byte []的数据= bos.toByteArray();
            串的timeStamp = GeneralUtil.generateTimeStamp();
            ByteArrayBody斌=新ByteArrayBody(数据,myMobileNo +_+的userName +_+的timeStamp +.JPG);
            MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
            multiPartEntityBuilder.addPart(uploadedfile1,斌);
            multiPartEntityBuilder.addPart(inviteId,新StringBody(inviteIdArrayList.get(0)的ToString(),Charset.forName(UTF-8)));
            httpcon.setEntity(multiPartEntityBuilder.build()); **错误**
            //执行POST请求到指定的URL
           // Htt的presponse HTT presponse = NULL;
          // HTT presponse = client.execute(后);
            httpcon.setRequestMethod(POST);
            httpcon.connect();
 

解决方案

我能得到我的多部分表单数据上传之后的事情了很多头刮伤和头发拉工作。 下面类用于多部分文件上传和它的作品。 注意:这不是一个问题,仅仅一个答案运算。

 公共类WebConnector {
    字符串边界=-------------+ System.currentTimeMillis的();
    私有静态最后弦乐LINE_FEED =\ r \ N的;
    私有静态最后弦乐TWO_HYPHENS = - ;


    私人StringBuilder的网址;
    私人字符串协议;
    私人的HashMap<字符串,字符串> PARAMS;
    私人的JSONObject POSTDATA;
    私人列表<字符串>的fileList;
    私人诠释计数= 0;
    私人DataOutputStream类之处;

    公共WebConnector(StringBuilder的URL,字符串的协议,
                        HashMap的<字符串,字符串>参数,可以把JSONObject POSTDATA){
        超();
        this.url =网址;
        this.protocol =协议;
        this.params = PARAMS;
        this.postData = POSTDATA;
        createServiceUrl();
    }

    公共WebConnector(StringBuilder的URL,字符串的协议,
                        HashMap的<字符串,字符串>参数,可以的JSONObject POSTDATA,列表和LT;字符串> fileList)中的{
        超();
        this.url =网址;
        this.protocol =协议;
        this.params = PARAMS;
        this.postData = POSTDATA;
        this.fileList =的fileList;
        createServiceUrl();
    }

    公共字符串connectToMULTIPART_POST_service(字符串postName){


        的System.out.println(>>>>>>>>>网址:+网址);

        StringBuilder的StringBuilder的=新的StringBuilder();

        字符串strResponse =;
        的InputStream的InputStream = NULL;
        HttpURLConnection类的URLConnection = NULL;

        尝试 {
            的URLConnection =(HttpURLConnection类)新的URL(url.toString())的openConnection()。
            urlConnection.setRequestProperty(接受,应用/ JSON);
            urlConnection.setRequestProperty(连接,关闭);
            urlConnection.setRequestProperty(用户代理,Mozilla的/ 5.0(兼容));
            urlConnection.setRequestProperty(授权,承载+ Config.getConfigInstance()getAccessToken());
            urlConnection.setRequestProperty(内容型,多部分/格式数据;边界=+界);

            urlConnection.setDoOutput(真正的);
            urlConnection.setDoInput(真正的);
            urlConnection.setUseCaches(假);
            urlConnection.setChunkedStreamingMode(1024);
            urlConnection.setRequestMethod(POST);
            DOS =新DataOutputStream类(urlConnection.getOutputStream());

            迭代器<字符串>键= postData.keys();
            而(keys.hasNext()){
                尝试 {
                    串的id =将String.valueOf(keys.next());
                    addFormField(ID,+ postData.get(ID));
                    的System.out.println(ID +:+ postData.get(ID));
                }赶上(JSONException E){
                    e.printStackTrace();
                }
            }
            尝试 {
                dos.writeBytes(LINE_FEED);
                dos.flush();
                dos.close();
            }赶上(IOException异常E){
                e.printStackTrace();
            }
            如果(的fileList =空&安培;!&安培; fileList.size()大于0&安培;&安培;!fileList.isEmpty()){
                的for(int i = 0; I< fileList.size();我++){

                    档案文件=新的文件(fileList.get(一));
                    如果(文件!= NULL);
                    addFilePart(照片[+ I +] [图片],文件);
                }
            }
            //形成日java.net.URL对象

            建立();
            urlConnection.connect();
            INT状态code = 0;
            尝试 {
                urlConnection.connect();
                状态code = urlConnection.getResponse code();
            }赶上(EOFException类E1){
                如果(计数小于5){
                    urlConnection.disconnect();
                    算上++;
                    字符串临时= connectToMULTIPART_POST_service(postName);
                    如果(临时=空&放大器;!&安培;!temp.equals()){
                        返回温度;
                    }
                }
            }赶上(IOException异常E){
                e.printStackTrace();
            }
            // 200重新presents HTTP OK
            如果(状态code == HttpURLConnection.HTTP_OK){
                的InputStream =新的BufferedInputStream(urlConnection.getInputStream());
                strResponse = readStream(InputStream的);
            } 其他 {
                的System.out.println(urlConnection.getResponseMessage());
                的InputStream =新的BufferedInputStream(urlConnection.getInputStream());
                strResponse = readStream(InputStream的);
            }
        }赶上(例外五){
            e.printStackTrace();
        } 最后 {
            尝试 {
                如果(NULL!=的InputStream)
                    inputStream.close();
            }赶上(IOException异常E){
            }
        }
        返回strResponse;
    }

    公共无效addFormField(字符串字段名,字符串值){
        尝试 {
            dos.writeBytes(TWO_HYPHENS +边界+ LINE_FEED);
            dos.writeBytes(内容处置:表格数据;名称= \+字段名+\+ LINE_FEED + LINE_FEED / * +价值+ LINE_FEED * /);
            /*dos.writeBytes("Content-Type:text / plain的;字符集= UTF-8+ LINE_FEED); * /
            dos.writeBytes(值+ LINE_FEED);
        }赶上(IOException异常E){
            e.printStackTrace();
        }

    }

    公共无效addFilePart(字符串字段名,文件uploadFile){
        尝试 {
            dos.writeBytes(TWO_HYPHENS +边界+ LINE_FEED);
            dos.writeBytes(内容处置:表格数据;名称= \+字段名+\;文件名= \+ uploadFile.getName()+\+ LINE_FEED);
            dos.writeBytes(LINE_FEED);

            的FileInputStream fstream的=新的FileInputStream(uploadFile);
            INT缓冲区大小= 1024;
            byte []的缓冲区=新的字节[BUFFERSIZE]
            INT长度= -1;

            而((长度= fStream.read(缓冲液))!=  -  1){
                dos.write(缓冲液,0,长度);
            }
            dos.writeBytes(LINE_FEED);
            dos.writeBytes(TWO_HYPHENS +边界+ TWO_HYPHENS + LINE_FEED);
        / *关闭流* /
            fStream.close();
        }赶上(IOException异常E){
            e.printStackTrace();
        }
    }

    公共无效addHeaderField(字符串名称,字符串值){
        尝试 {
            dos.writeBytes(名字+:+价值+ LINE_FEED);
        }赶上(IOException异常E){
            e.printStackTrace();
        }

    }

    公共无效的构建(){
        尝试 {
            dos.writeBytes(LINE_FEED);
            dos.flush();
            dos.close();
        }赶上(IOException异常E){
            e.printStackTrace();
        }
    }

    私有静态字符串readStream(InputStream中的){
        StringBuilder的SB =新的StringBuilder();
        尝试 {
            的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(在));
            字符串nextLine =;
            而((nextLine = reader.readLine())!= NULL){
                sb.append(nextLine);
            }
        / *关闭流* /
            如果(NULL!= IN){
                附寄();
            }
        }赶上(IOException异常E){
            e.printStackTrace();
        }
        返回sb.toString();
    }

    私人无效createServiceUrl(){
        如果(空== PARAMS){
            返回;
        }
        最后的迭代器<为Map.Entry<字符串,字符串>>它= params.entrySet()迭代器()。
        布尔isParam = FALSE;
        而(it.hasNext()){
            最后的Map.Entry<字符串,字符串> mapEnt =(Map.Entry的<字符串,字符串>)it.next();
            url.append(mapEnt.getKey());
            url.append(=);
            尝试 {
                url.append(URLEn coder.en code(mapEnt.getValue(),UTF-8));
            }赶上(UnsupportedEncodingException E){
                e.printStackTrace();
            }赶上(NullPointerException异常E){
                e.printStackTrace();
            }
            url.append(WSConstants.AMPERSAND);
            isParam = TRUE;
        }
        如果(isParam){
            url.deleteCharAt(url.length() -  1);
        }
    }

}
 

i am trying to change HTTPClient deprecated code but i get error on setEntity because its dapricated and i dont know how to paas MultipartEntityBuilder by new httpConnectionUrl. my old deprecated code snippt

    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(imagePostUrl);

        for (String fileName : fileNameArrayList) {

            File file = new File(fileName);
            // 1st

            int quality = GeneralUtil.getQualityOfImage(file);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            if (quality <= 25) { // This means image file size is in MB's so we need to avoide out of memory issues.

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = false;
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inDither = true;
                try {
                    bitmap = BitmapFactory.decodeFile(file.getPath(), options);
                } catch (OutOfMemoryError E) {
                    System.gc();
                    bitmap = GeneralUtil.decodeFile(file);

                }

                bitmap.compress(CompressFormat.JPEG, quality, bos);
                bitmap.recycle();
                bitmap = null;

            } else {

                try {
                    bitmap = BitmapFactory.decodeFile(file.getPath());
                    bitmap.compress(CompressFormat.JPEG, quality, bos);
                    bitmap.recycle();
                    bitmap = null;
                } catch (OutOfMemoryError E) {
                    System.gc();

                    try {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = false;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = true;

                        bitmap = BitmapFactory.decodeFile(file.getPath(), options);
                        bitmap.compress(CompressFormat.JPEG, quality, bos);
                        bitmap.recycle();
                        bitmap = null;
                    } catch (OutOfMemoryError ex) {

                        bitmap = GeneralUtil.decodeFile(file);
                        bitmap.compress(CompressFormat.JPEG, quality, bos);
                        bitmap.recycle();
                        bitmap = null;
                        throw new Exception();
                    }
                }
            }

            byte[] data = bos.toByteArray();
            String timeStamp = GeneralUtil.generateTimeStamp();
            ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");

            MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
            multiPartEntityBuilder.addPart("uploadedfile1", bin);
            multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
            post.setEntity(multiPartEntityBuilder.build());
            HttpResponse httpResponse = null;
            httpResponse = client.execute(post);
            InputStream inputStream = null;
            inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null)
                result.add(convertInputStreamToString(inputStream));
            else
                result.add("Did not work!");
        }

my new not working code snippt

    try {
        HttpURLConnection httpcon = (HttpURLConnection) ((new URL(imagePostUrl).openConnection()));
        httpcon.setDoOutput(true);
        for (String fileName : fileNameArrayList) {
            File file = new File(fileName);
            int quality = GeneralUtil.getQualityOfImage(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            if (quality <= 25) { 
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = false;
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                options.inDither = true;
                try {
                    bitmap = BitmapFactory.decodeFile(file.getPath(), options);
                } catch (OutOfMemoryError E) {
                    System.gc();
                    bitmap = GeneralUtil.decodeFile(file);

                }
                bitmap.compress(CompressFormat.JPEG, quality, bos);
                bitmap.recycle();
                bitmap = null;

            } else {

                try {
                    bitmap = BitmapFactory.decodeFile(file.getPath());
                    bitmap.compress(CompressFormat.JPEG, quality, bos);
                    bitmap.recycle();
                    bitmap = null;
                } catch (OutOfMemoryError E) {
                    System.gc();

                    try {
                        BitmapFactory.Options options = new BitmapFactory.Options();
                        options.inJustDecodeBounds = false;
                        options.inPreferredConfig = Bitmap.Config.RGB_565;
                        options.inDither = true;

                        bitmap = BitmapFactory.decodeFile(file.getPath(), options);
                        bitmap.compress(CompressFormat.JPEG, quality, bos);
                        bitmap.recycle();
                        bitmap = null;
                    } catch (OutOfMemoryError ex) {

                        bitmap = GeneralUtil.decodeFile(file);
                        bitmap.compress(CompressFormat.JPEG, quality, bos);
                        bitmap.recycle();
                        bitmap = null;
                        throw new Exception();
                    }


                }
            }
            byte[] data = bos.toByteArray();
            String timeStamp = GeneralUtil.generateTimeStamp();
            ByteArrayBody bin = new ByteArrayBody(data, myMobileNo + "_" + userName + "_" + timeStamp + ".jpg");
            MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
            multiPartEntityBuilder.addPart("uploadedfile1", bin);
            multiPartEntityBuilder.addPart("inviteId", new StringBody(inviteIdArrayList.get(0).toString(), Charset.forName("UTF-8")));
            httpcon.setEntity(multiPartEntityBuilder.build()); **error**
            // Execute POST request to the given URL
           // HttpResponse httpResponse = null;
          //  httpResponse = client.execute(post);
            httpcon.setRequestMethod("POST");
            httpcon.connect();

解决方案

I was able to get my Multipart Form Data upload thing to work after a lot of head scratching and hair pulling. Below class is used for multipart file uploading and it works. NB: This is not a question, merely an answer to the op.

public class WebConnector {
    String boundary = "-------------" + System.currentTimeMillis();
    private static final String LINE_FEED = "\r\n";
    private static final String TWO_HYPHENS = "--";


    private StringBuilder url;
    private String protocol;
    private HashMap<String, String> params;
    private JSONObject postData;
    private List<String> fileList;
    private int count = 0;
    private DataOutputStream dos;

    public WebConnector(StringBuilder url, String protocol,
                        HashMap<String, String> params, JSONObject postData) {
        super();
        this.url = url;
        this.protocol = protocol;
        this.params = params;
        this.postData = postData;
        createServiceUrl();
    }

    public WebConnector(StringBuilder url, String protocol,
                        HashMap<String, String> params, JSONObject postData, List<String> fileList) {
        super();
        this.url = url;
        this.protocol = protocol;
        this.params = params;
        this.postData = postData;
        this.fileList = fileList;
        createServiceUrl();
    }

    public String connectToMULTIPART_POST_service(String postName) {


        System.out.println(">>>>>>>>>url : " + url);

        StringBuilder stringBuilder = new StringBuilder();

        String strResponse = "";
        InputStream inputStream = null;
        HttpURLConnection urlConnection = null;

        try {
            urlConnection = (HttpURLConnection) new URL(url.toString()).openConnection();
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("Connection", "close");
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
            urlConnection.setRequestProperty("Authorization", "Bearer " + Config.getConfigInstance().getAccessToken());
            urlConnection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + boundary);

            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            urlConnection.setChunkedStreamingMode(1024);
            urlConnection.setRequestMethod("POST");
            dos = new DataOutputStream(urlConnection.getOutputStream());

            Iterator<String> keys = postData.keys();
            while (keys.hasNext()) {
                try {
                    String id = String.valueOf(keys.next());
                    addFormField(id, "" + postData.get(id));
                    System.out.println(id + " : " + postData.get(id));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            try {
                dos.writeBytes(LINE_FEED);
                dos.flush();
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (fileList != null && fileList.size() > 0 && !fileList.isEmpty()) {
                for (int i = 0; i < fileList.size(); i++) {

                    File file = new File(fileList.get(i));
                    if (file != null) ;
                    addFilePart("photos[" + i + "][image]", file);
                }
            }
            // forming th java.net.URL object

            build();
            urlConnection.connect();
            int statusCode = 0;
            try {
                urlConnection.connect();
                statusCode = urlConnection.getResponseCode();
            } catch (EOFException e1) {
                if (count < 5) {
                    urlConnection.disconnect();
                    count++;
                    String temp = connectToMULTIPART_POST_service(postName);
                    if (temp != null && !temp.equals("")) {
                        return temp;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 200 represents HTTP OK
            if (statusCode == HttpURLConnection.HTTP_OK) {
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                strResponse = readStream(inputStream);
            } else {
                System.out.println(urlConnection.getResponseMessage());
                inputStream = new BufferedInputStream(urlConnection.getInputStream());
                strResponse = readStream(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != inputStream)
                    inputStream.close();
            } catch (IOException e) {
            }
        }
        return strResponse;
    }

    public void addFormField(String fieldName, String value) {
        try {
            dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"" + LINE_FEED + LINE_FEED/*+ value + LINE_FEED*/);
            /*dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + LINE_FEED);*/
            dos.writeBytes(value + LINE_FEED);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void addFilePart(String fieldName, File uploadFile) {
        try {
            dos.writeBytes(TWO_HYPHENS + boundary + LINE_FEED);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\";filename=\"" + uploadFile.getName() + "\"" + LINE_FEED);
            dos.writeBytes(LINE_FEED);

            FileInputStream fStream = new FileInputStream(uploadFile);
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];
            int length = -1;

            while ((length = fStream.read(buffer)) != -1) {
                dos.write(buffer, 0, length);
            }
            dos.writeBytes(LINE_FEED);
            dos.writeBytes(TWO_HYPHENS + boundary + TWO_HYPHENS + LINE_FEED);
        /* close streams */
            fStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void addHeaderField(String name, String value) {
        try {
            dos.writeBytes(name + ": " + value + LINE_FEED);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void build() {
        try {
            dos.writeBytes(LINE_FEED);
            dos.flush();
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String readStream(InputStream in) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String nextLine = "";
            while ((nextLine = reader.readLine()) != null) {
                sb.append(nextLine);
            }
        /* Close Stream */
            if (null != in) {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private void createServiceUrl() {
        if (null == params) {
            return;
        }
        final Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
        boolean isParam = false;
        while (it.hasNext()) {
            final Map.Entry<String, String> mapEnt = (Map.Entry<String, String>) it.next();
            url.append(mapEnt.getKey());
            url.append("=");
            try {
                url.append(URLEncoder.encode(mapEnt.getValue(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            url.append(WSConstants.AMPERSAND);
            isParam = true;
        }
        if (isParam) {
            url.deleteCharAt(url.length() - 1);
        }
    }

}

这篇关于MultipartEntityBuilder从Android的HttpURLConnection的发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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