首页 > 代码库 > android 向服务器Get和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= http://www.mamicode.com/URLEncoder.encode(params.get(key),"UTF-8");>