package com.zzy.infobackup.utils.httpUtils;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;
import android.util.Log;
import com.zzy.infobackup.model.Constant;
/**
* class name:HttpUpload<BR>
* class description:Http上传类<BR>
* PS: <BR>
* Date:2013-4-18<BR>
*
* @version 1.0
* @author wyr
*/
public class HttpUpload {
private static final int connecttime = 6000;
/**
* 上传文件
*
* @param uploadUrl
* 上传的URL
* @param srcPath
* 待上传文件的路径
* @param userName
* 用户
* @return
* */
public static String upLoad(String uploadUrl, String srcPath,
Map<String, String> params) {
String CHARSET = "UTF-8";
String result = null;
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url
.openConnection();
// 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
// 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
// 允许输入输出流
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
// 使用POST方法
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(
httpURLConnection.getOutputStream());
// 设置请求参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(twoHyphens);
sb.append(boundary);
sb.append(end);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + end);
sb.append("Content-Type: text/plain; charset=" + CHARSET + end);
sb.append("Content-Transfer-Encoding: 8bit" + end);
sb.append(end);
sb.append(entry.getValue());
sb.append(end);
}
dos.write(sb.toString().getBytes());
// 发送文件数据
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
// 读取文件
while ((count = fis.read(buffer)) != -1) {
dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
// 获取响应码
int code = httpURLConnection.getResponseCode();
InputStream is = null;
if (code == 200) {
is = httpURLConnection.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = is.read()) != -1) {
sb2.append((char) ch);
}
result = sb2.toString();
Log.e("上传结果:", result);
}
httpURLConnection.disconnect();
if (is != null) {
is.close();
}
if (dos != null) {
dos.close();
}
} catch (Exception e) {
Log.e("Exception:", e.getMessage());
e.printStackTrace();
}
return result;
}
public static String netPost(String url, Map<String, String> rawParams) {
HttpClient httpClient = HttpUpload.getClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (String key : rawParams.keySet()) {
// 封装请求参数
params.add(new BasicNameValuePair(key, rawParams.get(key)));
}
// 设置请求参数
try {
post.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
HttpResponse httpResponse;
httpResponse = httpClient.execute(post);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
// 获取服务器响应字符串
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println("result---->" + result);
return result;
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Constant.TIME_OUT;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return Constant.ERROR;
}
return null;
}
private static HttpClient getClient() {
BasicHttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connecttime);
HttpConnectionParams.setSoTimeout(httpParams, connecttime);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
}
Android中的文件上传
最新推荐文章于 2024-04-09 07:37:28 发布