Android httpclient文件上传数据损坏和超时问题

Android httpclient文件上传数据损坏和超时问题,第1张

概述我在 Android中上传图片时遇到问题. 我使用apache httpmime 4.1 lib 代码是这样的: MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);reqEntity.addPart("image", new FileBody(new File(Andorr 我在 Android中上传图片时遇到问题.

我使用apache httpmime 4.1 lib
代码是这样的:

multipartentity reqEntity = new multipartentity(httpMultipartMode.broWSER_COMPATIBLE);reqEntity.addPart("image",new fileBody(new file(AndorraApplication.getPhotosPath() + "/" + entity.getfilename()),"image/jpeg"));resp = NetworkUtils.sendhttpRequestMultipart(EXPORT_PHOTOS_URI,reqEntity);

NetworkUtils类:

public class NetworkUtils {    public static final int REGISTRATION_TIMEOUT = 3 * 1000;     public static final int WAIT_TIMEOUT = 5 * 1000;    public static httpResponse sendhttpRequestMultipart(String uri,multipartentity entity) {        httpClIEnt mhttpClIEnt = new DefaulthttpClIEnt();        final httpParams params = mhttpClIEnt.getParams();        httpconnectionParams.setConnectionTimeout(params,REGISTRATION_TIMEOUT);        httpconnectionParams.setSoTimeout(params,WAIT_TIMEOUT);        ConnManagerParams.setTimeout(params,WAIT_TIMEOUT);        httpPost post = new httpPost(uri);        post.addheader(entity.getContentType());        post.setEntity(entity);        httpResponse resp = mhttpClIEnt.execute(post);    }}

有时一切都可以正常工作,但有时(特别是缓慢的连接),图像被上传非常损坏.例子在这里:http://pixelbirthcloud.com/574_orig.jpg

它不会抛出任何异常.上传的文件的长度与原始文件的长度相同..尝试将MIME类型更改为应用程序/八位字节流或删除它.尝试玩超时.结果仍然相同最终用户几乎全部上传损坏的图像(尽管我设法只得到bronem图像只有2次).图像大小首先是2.5兆,但是我将其缩小到500-700 kb.没有解决问题.

没有尝试改变apache的图书馆..也许这是问题..但就我所读的网络而言,没有人在使用httpmime库.

怎么可能?我完全迷失了:(

另一个问题是超时有时不奏效.

就像这样说:
httpResponse resp = mhttpClIEnt.execute(post);
并且我禁用3g连接,它等待像17-20分钟而不是3或5秒..然后抛出异常.尝试不同的方法.喜欢这个:

httpParams params = new BasichttpParams();        httpProtocolParams.setVersion(params,httpVersion.http_1_1);        httpProtocolParams.setContentCharset(params,http.UTF_8);        httpProtocolParams.setUseExpectContinue(params,false);          httpconnectionParams.setConnectionTimeout(params,10000);        httpconnectionParams.setSoTimeout(params,10000);        ConnManagerParams.setMaxTotalConnections(params,5);        ConnManagerParams.setTimeout(params,30000);        SchemeRegistry registry = new SchemeRegistry();        registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));        registry.register(new Scheme("https",80));        ThreadSafeClIEntConnManager manager = new ThreadSafeClIEntConnManager(params,registry);        httpClIEnt httpclIEnt = new DefaulthttpClIEnt(manager,params);

但仍然不工作:)

解决方法 查看我的图像上传程序代码,它对我来说非常有用
这个类将文件上传到服务器加上,最后读取XML回复也.
根据您的要求过滤代码.它对我来说非常顺利
package com.classifIEds;import java.io.DataOutputStream;import java.io.file;import java.io.fileinputStream;import java.io.IOException;import java.net.httpURLConnection;import java.net.MalformedURLException;import java.net.URL;import javax.xml.parsers.ParserConfigurationException;import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.inputSource;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler;import androID.util.Log;public class Uploader {    private String Tag = "UPLOADER";    private String urlString ;//= "YOUR_ONliNE_PHP";    httpURLConnection conn;    String exsistingfilename ;    private voID uploadImageData(String existingfilename,String urlString)    {        String lineEnd = "\r\n";        String twoHyphens = "--";        String boundary = "*****";        try {            // ------------------ CLIENT REQUEST            Log.e(Tag,"InsIDe second Method");            fileinputStream fileinputStream = new fileinputStream(new file(                    exsistingfilename));            // 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);            DataOutputStream dos = new DataOutputStream(conn.getoutputStream());            dos.writeBytes(twoHyphens + boundary + lineEnd);            dos                    .writeBytes("Content-disposition: post-data; name=uploadedfile;filename="                            + exsistingfilename + "" + lineEnd);            dos.writeBytes(lineEnd);            Log.v(Tag,"headers are written");            // create a buffer of maximum size            int bytesAvailable = fileinputStream.available();            int maxBufferSize = 1000;            // int bufferSize = Math.min(bytesAvailable,maxBufferSize);            byte[] buffer = new byte[bytesAvailable];            // read file and write it into form...            int bytesRead = fileinputStream.read(buffer,bytesAvailable);            while (bytesRead > 0) {                dos.write(buffer,bytesAvailable);                bytesAvailable = fileinputStream.available();                bytesAvailable = Math.min(bytesAvailable,maxBufferSize);                bytesRead = fileinputStream.read(buffer,bytesAvailable);            }            // send multipart form data necesssary after file data...            dos.writeBytes(lineEnd);            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);            // close streams            Log.v(Tag,"file is written");            fileinputStream.close();            dos.flush();            dos.close();        } catch (MalformedURLException ex) {            Log.e(Tag,"error: " + ex.getMessage(),ex);        }        catch (IOException ioe) {            Log.e(Tag,"error: " + ioe.getMessage(),ioe);        }        SAXParserFactory spf = SAXParserFactory.newInstance();        SAXParser sp = null;        try {            sp = spf.newSAXParser();        } catch (ParserConfigurationException e) {            // Todo auto-generated catch block            e.printstacktrace();        } catch (SAXException e) {            // Todo auto-generated catch block            e.printstacktrace();        }        // Get the XMLReader of the SAXParser we created.        XMLReader xr = null;        try {            xr = sp.getXMLReader();        } catch (SAXException e) {            // Todo auto-generated catch block            e.printstacktrace();        }        // Create a new ContentHandler and apply it to the XML-Reader        MyExampleHandler1 myExampleHandler = new MyExampleHandler1();        xr.setContentHandler(myExampleHandler);        // Parse the xml-data from our URL.         try {            xr.parse(new inputSource(conn.getinputStream()));        //xr.parse(new inputSource(new java.io.fileinputStream(new java.io.file("login.xml"))));         } catch (MalformedURLException e) {            Log.d("Net disconnected","Netdisconeeted");            // Todo auto-generated catch block            e.printstacktrace();        } catch (IOException e) {            Log.d("Net disconnected","Netdisconeeted");            // Todo auto-generated catch block            e.printstacktrace();        } catch (SAXException e) {            Log.d("Net disconnected","Netdisconeeted");            // Todo auto-generated catch block            e.printstacktrace();        }        // Parsing has finished.    }    public Uploader(String existingfilename,boolean isImageUploading,String urlString ) {        this.exsistingfilename = existingfilename;        this.urlString = urlString;    }    class MyExampleHandler1 extends DefaultHandler    {    // ===========================================================    // Methods    // ===========================================================    @OverrIDe    public voID startdocument() throws SAXException {    }    @OverrIDe    public voID enddocument() throws SAXException {        // nothing to do    }    @OverrIDe    public voID startElement(String namespaceURI,String localname,String qname,Attributes atts) throws SAXException {    }    /** Gets be called on closing Tags like:     * </tag> */    @OverrIDe    public voID endElement(String namespaceURI,String qname)              throws SAXException {    }    /** Gets be called on the following structure:     * <tag>characters</tag> */    @OverrIDe    public voID characters(char ch[],int start,int length) {     }    }}
总结

以上是内存溢出为你收集整理的Android httpclient文件上传数据损坏和超时问题全部内容,希望文章能够帮你解决Android httpclient文件上传数据损坏和超时问题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1132692.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存