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

开发者在使用Apache HttpClient 4.1的MultipartEntity进行Android应用中图片上传时遇到问题,文件长度匹配但上传图片损坏。尝试了多种解决方案如修改MIME类型、调整超时设置,但问题依旧,求助于社区可能的解决方案和库选择建议。
摘要由CSDN通过智能技术生成

我在

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);

}

}

它不会抛出任何异常.上传的文件的长度与原始文件的长度相同..尝试将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:

* */

@Override

public void endElement(String namespaceURI,String qName)

throws SAXException {

}

/** Gets be called on the following structure:

* characters */

@Override

public void characters(char ch[],int start,int length) {

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值