android2.3以后都要用AsyncTask了,所以自己写了个帮助类。可以上传图片的
package com.http.util;
import java.io.File;
import java.nio.charset.Charset;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
/**
* 2.3之后的安卓版本 获取网址内容
* 利用了新增加的辅助类AsyncTask
*/
//构造函数AsyncTask<Params, Progress, Result>参数说明:
//Params 启动任务执行的输入参数
//Progress 后台任务执行的进度
//Result 后台计算结果的类型
public class UploadImgAndInforAsyncTask extends AsyncTask<String, Integer, String>{
private File myfile;
private String requestURL;
private String info;
//为AsyncTask创建传递参数
public UploadImgAndInforAsyncTask(String info,File file,String requestURL) {
this.myfile = file;
this.requestURL = requestURL;
this.info = info;
}
//为AsyncTask自定义监听器 用来再确认图片上传成功后返回方法到Activity
public static interface UploadListener { //定义接口函数
void backtoActivity(Object data);
// void aaa();//公共函数用于设置监听
}
public UploadListener uploadListener;
public void setUploadListener(UploadListener uploadListener) {
this.uploadListener = uploadListener;
}
//onPreExecute()方法用于在执行异步任务前,主线程做一些准备工作
@Override
protected void onPreExecute() {
}
//doInBackground()方法用于在执行异步任务,不可以更改主线程中UI
@Override
protected String doInBackground(String... params) {
try
{
HttpPost httpPost = ConnNet.getHttPost(requestURL);//到辅助类转换httpPos
MultipartEntity mpEntity = new MultipartEntity();
mpEntity.addPart("picture", new FileBody(myfile, "image/*", "UTF-8"));//图片
mpEntity.addPart("info", new StringBody(info,Charset.forName("UTF-8")));//字符串
httpPost.setEntity(mpEntity);
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse = client.execute(httpPost);//发送
// if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8"); //接收
System.out.println("结果为:"+result);
return result.toString();
}
}
catch(Exception e)
{
System.out.println("出bug了。。。");
}
System.out.println("上传失败,请检查网络连接");
return null;
}
//onPostExecute()方法用于异步任务执行完成后,在主线程中执行的操作
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Toast.makeText(getApplicationContext(), "调用onPostExecute()方法--->异步任务执行完毕", 0).show();
//textView显示网络请求结果
if(result != null)
{
System.out.println("上传成功!返回结果是:"+ result);
uploadListener.backtoActivity(result);
// dataDownloadListener.aaa();
}
else {
System.out.println("上传失败,没有从服务器获得相应连接");
uploadListener.backtoActivity(null);
}
}
//onProgressUpdate()方法用于更新异步执行中,在主线程中处理异步任务的执行信息
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
//onCancelled()方法用于异步任务被取消时,在主线程中执行相关的操作
@Override
protected void onCancelled() {
super.onCancelled();
System.out.println("调用onCancelled()方法--->异步任务被取消");
}
帮助类Connet得到网址:
package com.http.util;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
/**
* 获取网络连接 connection
*/
public class ConnNet
{
//将路径定义为一个常量,修改的时候也好更改
public static String request_Send_PictureAndMessage_URL = "http://192.168.112.117:8080/HyhealthServer/uploadServer";//图片上传服务器路径
public static String request_Get_Message_URL = "http://192.168.112.117:8080/HyhealthServer/downloadServer";//获取结果界面
//通过url获取网络连接 connection
public static HttpURLConnection getConn(String requestURL)
{
String boundary ="*****";
try
{
URL url =new URL(requestURL);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
return con;
}catch(Exception e){
}
return null;
}
public static HttpPost getHttPost(String url){
HttpPost httpPost = new HttpPost(url);
System.out.println("ConnNet的url:"+url);
return httpPost;
}
public static HttpGet getHttpGet (String url){
HttpGet httpGet = new HttpGet(url);
return httpGet;
}
}
在activity中调用的时候这样:
UploadImgAndInforAsyncTask uploadImgAndInforAsyncTask = new UploadImgAndInforAsyncTask(info,myfFile,ConnNet.request_Send_PictureAndMessage_URL);
uploadImgAndInforAsyncTask.setUploadListener(new UploadListener()
{
@SuppressWarnings("unchecked")
@Override
public void backtoActivity(Object data) {
<span style="white-space:pre"> </span>这里就是通过<span style="font-family: Arial, Helvetica, sans-serif;">AsyncTask类返回的监听的值了</span>
}
});
uploadImgAndInforAsyncTask.execute(ConnNet.request_Send_PictureAndMessage_URL);
服务器上这样获得图片并保存
package com.wy.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.wy.helper.JsonHelper;
import com.wy.model.AndroidHyhealth;
import com.wy.model.Hyhealth;
import com.wy.service.Myservice;
@Component
public class UploadServer extends HttpServlet {
@Autowired
private Myservice myservice;
private String paramValue;
private String filePath;
private String fileName;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
//普通文本信息处理
String paramName = item.getFieldName();
paramValue = item.getString();
System.out.println(paramName + ":" + paramValue);
} else {
//上传文件信息处理
String loadpath=request.getSession().getServletContext().getRealPath("/")+"upload"; //上传文件存放目录
fileName = item.getName();
byte[] data = item.get();
System.out.println("name="+fileName);
int point = fileName.indexOf(".");//重命名
fileName=(new Date()).getTime()+fileName.substring(point,fileName.length());
filePath = loadpath+"/"+fileName;//文件存放位置+文件名
FileOutputStream fos = new FileOutputStream(filePath);//写入文件
fos.write(data);
fos.close();
}
}
} catch (FileUploadException e) {
PrintWriter out = response.getWriter();
out.println("false");
out.flush();
out.close();
e.printStackTrace();
}
//给Android返回信息
PrintWriter out = response.getWriter();
out.println("true");
out.flush();
out.close();
}
public void init() throws ServletException {
// Put your code here
}
public UploadServer() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
整个流程就是这样完成了