码迷,mamicode.com
首页 > 移动开发 > 详细

android 向服务器Get和Post请求的两种方式,android向服务器发送文件,自己组装协议和借助第三方开源

时间:2014-08-01 19:56:22      阅读:343      评论:0      收藏:0      [点我收藏+]

标签:android post文件   android向服务器发送文件   android get post请求   android发送图片   

/** 
 * @author intbird@163.com 
 * @time 20140606 
 */ 
package com.intbird.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
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.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;

public class ConnInternet {
	/**
	 * 开始连接
	 */
	public static int HTTP_STATUS_START=0;
	/**
	 * 连接过程出错
	 */
	public static int HTTP_STATUS_ERROR=400;
	/**
	 * 请求成功,返回数据
	 */
	public static int HTTP_STATUS_REULTOK=200;
	/**
	 * 服务器未响应
	 */
	public static int HTTP_STATUS_NORESP=500;
	
	/**
	 * 普通GET请求
	 * @param api
	 * @param callBack
	 */
	public static void get1(final String api,final ConnInternetCallback callBack) {
		final Handler handler=getHandle(api, callBack);
		new Thread(){
			@Override
			public void run() {
				Message msg=handler.obtainMessage(HTTP_STATUS_START, "开始连接");
				try {
					URL url = new URL(api);
					HttpURLConnection urlConn =  (HttpURLConnection) url.openConnection();
					int resCode=urlConn.getResponseCode();
					if(resCode!=HTTP_STATUS_REULTOK){
						msg.what=HTTP_STATUS_NORESP;
						msg.obj=resCode;
						handler.sendMessage(msg);
						return ;
					}
					InputStreamReader inStream=new InputStreamReader(urlConn.getInputStream());
					BufferedReader buffer=new BufferedReader(inStream);
					
					String result="";
					String inputLine=null;
					while((inputLine=buffer.readLine())!=null){
						result+=inputLine;
					}
					msg.what=HTTP_STATUS_REULTOK;
				    msg.obj=URLDecoder.decode(result,"UTF-8");
				    
					inStream.close();
					urlConn.disconnect();
				} catch (Exception ex) {
					msg.what=HTTP_STATUS_ERROR;
				    msg.obj=ex.getMessage().toString();
				}
				finally{
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	public void get3(final String api,final ConnInternetCallback callBack) {
		final Handler handler=getHandle(api, callBack);
		new Thread(){
			@Override
			public void run() {
				Message msg=handler.obtainMessage(HTTP_STATUS_START, "开始连接");
				try {
					HttpGet httpGet=new HttpGet(api);
					HttpClient httpClient = new DefaultHttpClient();
					HttpResponse httpResp = httpClient.execute(httpGet);

					int resCode=httpResp.getStatusLine().getStatusCode();
					if(resCode!=HTTP_STATUS_REULTOK){
						msg.what=HTTP_STATUS_NORESP;
						msg.obj=resCode;
						handler.sendMessage(msg);
						return ;
					}
					msg.what=HTTP_STATUS_REULTOK;
					msg.obj= EntityUtils.toString(httpResp.getEntity());
					
				}catch (Exception e) {
					msg.what=HTTP_STATUS_ERROR;
					msg.obj= e.getMessage();
				}
				finally{
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	private static Handler getHandle(final String api,final ConnInternetCallback callBack){
		return new Handler() {
			@Override
			public void handleMessage(Message message) {
				//不 在 这里写!
				callBack.callBack(message.what,api, message.obj.toString());
			}
		};
	}

	/**
	 * 简单类型,只进行文字信息的POST;
	 * @param api api地址
	 * @param params 仅字段参数
	 * @param callBack 返回调用;
	 */
	public static void post1(final String api,final HashMap<String,String> params,final ConnInternetCallback callBack){
		final Handler handler=getHandle(api, callBack);
		new Thread(){
			@Override
			public void run() {
				Message msg=handler.obtainMessage(HTTP_STATUS_START,"开始连接");
				try {
					URL url=new URL(api);
					HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
					urlConn.setDoInput(true);
					urlConn.setDoOutput(true);
					urlConn.setRequestMethod("POST");
					urlConn.setUseCaches(false);
					urlConn.setInstanceFollowRedirects(true);
					urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
					urlConn.setRequestProperty("Charset", "UTF-8");
					
					urlConn.connect();
		            DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  
		            Iterator<String> iterator=params.keySet().iterator();
		            while(iterator.hasNext()){
		            	String key= iterator.next();
		            	String value= URLEncoder.encode(params.get(key),"UTF-8");
		            	out.write((key+"="+value+"&").getBytes()); 
		             }
		            out.flush();  
		            out.close();  
		            
		        	int resCode=urlConn.getResponseCode();
					if(resCode!=HTTP_STATUS_REULTOK){
						msg.what=HTTP_STATUS_NORESP;
						msg.obj=resCode;
						handler.sendMessage(msg);
						return ;
					}
		            String result="";
		            String readLine=null;
		            InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());
		            BufferedReader bufferReader=new BufferedReader(inputStream);
		            while((readLine=bufferReader.readLine())!=null){
		            	result+=readLine;
		            }
		            msg.what=HTTP_STATUS_REULTOK;
			        msg.obj=URLDecoder.decode(result,"UTF-8");
		            inputStream.close();
		            bufferReader.close();
		            urlConn.disconnect();
				}catch(Exception ex){
					msg.what=HTTP_STATUS_ERROR;
				    msg.obj=ex.getMessage().toString()+".";
				}
				finally{
		            handler.sendMessage(msg);
				}
			}
		}.start();
	}

	/**
	 * 自定义文字和文件传输协议[示例在函数结尾];
	 * @param apiUrl api地址
	 * @param mapParams 文字字段参数
	 * @param listUpFiles 多文件参数
	 * @param callBack 返回调用;
	 */
	public static void post2(final String apiUrl,final HashMap<String,String> mapParams,final ArrayList<ConnInternetUploadFile> listUpFiles,ConnInternetCallback callBack){
		final Handler handler=getHandle(apiUrl, callBack);
		new Thread(new Runnable() {
			public void run() {
				Message msg=handler.obtainMessage(HTTP_STATUS_START, "开始连接");
				
				String BOUNDARY="———7d4a6454354fe54scd";
				String PREFIX="--";
				String LINE_END="\r\n";
				
				try{
					URL url=new URL(apiUrl);
					HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
					urlConn.setDoOutput(true);
					urlConn.setDoInput(true);
					urlConn.setUseCaches(false);
					urlConn.setRequestMethod("POST");
					urlConn.setRequestProperty("Connection", "Keep-Alive");
					urlConn.setRequestProperty("Charset", "UTF-8");
					urlConn.setRequestProperty("Content-Type","multipart/form-data ;boundary="+BOUNDARY);
					
					DataOutputStream outStream=new DataOutputStream(urlConn.getOutputStream());

					for(Map.Entry<String,String> entry:mapParams.entrySet()){
						StringBuilder sbParam=new StringBuilder();
						sbParam.append(PREFIX);
						sbParam.append(BOUNDARY);
						sbParam.append(LINE_END);
						sbParam.append("Content-Disposition:form-data;name=\""+ entry.getKey()+"\""+LINE_END);
						sbParam.append("Content-Transfer-Encoding: 8bit" + LINE_END);
						sbParam.append(LINE_END);
						sbParam.append(entry.getValue());
						sbParam.append(LINE_END);
						outStream.write(sbParam.toString().getBytes());
					}
					
					for(ConnInternetUploadFile file:listUpFiles){
						StringBuilder sbFile=new StringBuilder();
						sbFile.append(PREFIX);
						sbFile.append(BOUNDARY);
						sbFile.append(LINE_END);
						sbFile.append("Content-Disposition:form-data;name=\""+file.getFormname()+"\";filename=\""+file.getFileName()+"\""+LINE_END);
						sbFile.append("Content-type:"+file.getContentType()+"\""+LINE_END);
						outStream.write(sbFile.toString().getBytes());
						writeFileToOutStream(outStream,file.getFileUrl());
						outStream.write(LINE_END.getBytes("UTF-8"));
					}
					
					byte[] end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes("UTF-8");
					outStream.write(end_data);
					outStream.flush();
					outStream.close();  
		        
					int resCode=urlConn.getResponseCode();
					if(resCode!=HTTP_STATUS_REULTOK){
						msg.what=HTTP_STATUS_NORESP;
						msg.obj=resCode;
						handler.sendMessage(msg);
						return ;
					}
		            String result="";
		            String readLine=null;
		            InputStreamReader inputStream=new InputStreamReader(urlConn.getInputStream());
		            BufferedReader bufferReader=new BufferedReader(inputStream);
		            while((readLine=bufferReader.readLine())!=null){
		            	result+=readLine;
		            }
		            msg.what=HTTP_STATUS_REULTOK;
			        msg.obj=URLDecoder.decode(result,"UTF-8");
			        inputStream.close();
		            bufferReader.close();
		            urlConn.disconnect();
				}catch(Exception ex){
					msg.what=HTTP_STATUS_ERROR;
				    msg.obj=ex.getMessage().toString();
				}
				finally{
		            handler.sendMessage(msg);
				}
			}
		}).start();
//		HashMap<String,String> params=new HashMap<String, String>();
//		params.put("pid", fileHelper.getShareProf("PassportId"));
//		params.put("json",postJson(text));
		
//		ArrayList<UploadFile> uploadFiles=new ArrayList<UploadFile>();
//		if(url.length()>0){
//			UploadFile upfile=new UploadFile(url,url,"Images");
//			uploadFiles.add(upfile);
//		}
//		Internet.post(Api.api_messageCreate, params,uploadFiles,new InternetCallback() {
//			@Override
//			public void callBack(int msgWhat, String api, String result) {
//				if(msgWhat==Internet.HTTP_STATUS_OK){
//					//跟新数据
//					adapter.notifyDataSetChanged();
//					//显示没有数据
//				}else showToast("网络错误");
//			}
//		});
	}
	
	/**
	 * 第三方Apache集成POST
	 * @param url api地址
	 * @param mapParams 参数
	 * @param callBack
	 */
	public static void post3(final String url, final HashMap<String,String> mapParams,final HashMap<String,String> mapFileInfo,ConnInternetCallback callBack) {
		final Handler handler=getHandle(url	, callBack);
		new Thread() {
			@Override
			public void run() {
				Message msg=handler.obtainMessage(HTTP_STATUS_START, "开始连接");
				try {
					HttpPost httpPost = new HttpPost(url);
			        //多类型;
					MultipartEntity multipartEntity = new MultipartEntity();  
			        //字段
			        Iterator<?> it=mapParams.keySet().iterator();
			        while(it.hasNext()){
				        String key=(String) it.next();
				        String value=mapParams.get(key);
					    multipartEntity.addPart(key,new StringBody(value,Charset.forName("UTF-8")));
			        }
			        //文件
			        it=mapFileInfo.keySet().iterator();
			        while(it.hasNext()){
			        	String key=(String)it.next();
			        	String value=mapFileInfo.get(key);
			        	multipartEntity.addPart(key, new FileBody(new File(value)));
			        }
			        
			        httpPost.setEntity(multipartEntity); 
					HttpClient httpClient = new DefaultHttpClient();
					HttpResponse httpResp = httpClient.execute(httpPost);
					
					int resCode=httpResp.getStatusLine().getStatusCode();
					if(resCode!=HTTP_STATUS_REULTOK){
						msg.what=HTTP_STATUS_NORESP;
						msg.obj=resCode;
						handler.sendMessage(msg);
						return ;
					}
					msg.what=HTTP_STATUS_REULTOK;
					msg.obj= EntityUtils.toString(httpResp.getEntity());
					
				}catch (Exception e) {
					msg.what=HTTP_STATUS_ERROR;
					msg.obj= e.getMessage();
				}
				finally{
					handler.sendMessage(msg);
				}
			}
		}.start();
	}
	
	public static Bitmap loadBitmapFromNet(String imgUrl,BitmapFactory.Options options){
		Bitmap bitmap = null;
		URL imageUrl = null;
		if (imgUrl == null || imgUrl.length() == 0) 	return null;
		try {
			imageUrl = new URL(imgUrl);
			URLConnection conn = imageUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			int length = conn.getContentLength();
			if (length != -1) {
				byte[] imgData = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) != -1) {
					System.arraycopy(temp, 0, imgData, destPos, readLen);
					destPos += readLen;
				}
				bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);
				options.inJustDecodeBounds=false;
				bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length,options);
			}
		} catch (IOException e) {
			return null;
		}
		return bitmap;
	}
	
	public static void writeFileToOutStream(DataOutputStream outStream,String url){
		try {
			InputStream inputStream = new FileInputStream(new File(url));
			int ch;
			while((ch=inputStream.read())!=-1){
				outStream.write(ch);
			}
			inputStream.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public interface ConnInternetCallback{
		public void callBack(int msgWhat,String api,String result);
	}
	
	public class ConnInternetUploadFile {
		private String filename;
		private String fileUrl;
		private String formname;
		private String contentType = "application/octet-stream";
													//image/jpeg
		public ConnInternetUploadFile(String filename, String fileUrl, String formname) {
			this.filename = filename;
			this.fileUrl=fileUrl;
			this.formname = formname;
		}

		public String getFileUrl() {
			return fileUrl;
		}

		public void setFileUrl(String url) {
			this.fileUrl=url;
		}

		public String getFileName() {
			return filename;
		}

		public void setFileName(String filename) {
			this.filename = filename;
		}

		public String getFormname() {
			return formname;
		}

		public void setFormname(String formname) {
			this.formname = formname;
		}

		public String getContentType() {
			return contentType;
		}
		public void setContentType(String contentType) {
			this.contentType = contentType;
		}
	}

}

android 向服务器Get和Post请求的两种方式,android向服务器发送文件,自己组装协议和借助第三方开源,布布扣,bubuko.com

android 向服务器Get和Post请求的两种方式,android向服务器发送文件,自己组装协议和借助第三方开源

标签:android post文件   android向服务器发送文件   android get post请求   android发送图片   

原文地址:http://blog.csdn.net/intbird/article/details/38338623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!