Android 网络请求框架,包涵get,post请求,from表单上传图片,基于okhtt封装的图片上传

貌似没什么好说的了,直接看代码吧!

1.get 与 post请求

package com.ax.okhttputils.okhttputils.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;


import com.ax.okhttputils.okhttputils.inface.HttpInface;
import com.ax.okhttputils.okhttputils.inface.HttpRunInface;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
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.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;



/**
 * Created by TP_zhao on 2017/4/11.
 */
public  class HttpUtils {

        static HttpUtils httpUtils;
    private static String strResult;
    private static String result;
    private static String results;
    private static RunnUtils runnUtils;



    public static HttpUtils getInstance(){

        if(httpUtils==null){
            httpUtils = new HttpUtils();
            return httpUtils;
        }
        return httpUtils;
    }
    static HttpInface httpinfces;

    /**
     *
     * @param URL 请求地址
     * @param map 上传的参数
     * @param httpinfce 回调接口的实例
     */
    public static void httpPost(final String URL, final Map<String, String> map, final HttpInface httpinfce){

        runnUtils = new RunnUtils();
        runnUtils.setInface(new HttpRunInface() {
            @Override
            public void carryHttp() {
                getData(URL, map, httpinfce);
            }
        });

        runnUtils.start();
    }

    private static void getData(String URL, Map<String, String> map, HttpInface httpinfce) {
        httpinfces = httpinfce;
        Set set = map.keySet();
        Iterator iter = set.iterator();
        final Iterator i = map.entrySet().iterator();
        List<NameValuePair> params = new ArrayList<NameValuePair>();   //Post运作传送变量必须用NameValuePair[]数组储存

        while (i.hasNext()) {
            Map.Entry entry = (Map.Entry)i.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
//            Log.i("xzzxxzzx",key+"  ----  "+value);
            params.add(new BasicNameValuePair(key,value));

        }
        String uriAPI = URL;  //声明网址字符串
        HttpPost httpRequest = new HttpPost(uriAPI);   //建立HTTP POST联机
        HttpResponse httpResponse = null;
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
        httpRequest.setParams(httpParameters);

        try {
            httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));   //发出http请求
             httpResponse = new DefaultHttpClient().execute(httpRequest);   //取得http响应
            if(httpResponse.getStatusLine().getStatusCode() == 200) {
                //获取字符串
                strResult = EntityUtils.toString(httpResponse.getEntity());
                handler.sendEmptyMessage(1);
                try {
                    httpRequest.clone();
                    Runtime.getRuntime().gc();
                } catch (CloneNotSupportedException z) {
                    z.printStackTrace();
                }
            }else{
                strResult = "-1";
                handler.sendEmptyMessage(6);
//                Log.i("post","网络连接失败");
                try {
                    httpRequest.clone();
                    Runtime.getRuntime().gc();
                } catch (CloneNotSupportedException z) {
                    z.printStackTrace();
                }
            }
        } catch(ConnectTimeoutException e){
            // 捕获超时异常 并反馈给调用者
            e.printStackTrace();
//            Toast.makeText(context,"网络状况不太好!",Toast.LENGTH_LONG).show();
            strResult = "-1";
            handler.sendEmptyMessage(6);
            try {
                httpRequest.clone();
                Runtime.getRuntime().gc();
            } catch (CloneNotSupportedException z) {
                z.printStackTrace();
            }
            try {
                httpRequest.clone();
                Runtime.getRuntime().gc();
            } catch (CloneNotSupportedException z) {
                z.printStackTrace();
            }
//            Log.i("post","网络连接失败");
        }catch (IOException e) {
            try {
                httpRequest.clone();
                Runtime.getRuntime().gc();
            } catch (CloneNotSupportedException z) {
                z.printStackTrace();
                strResult = "-1";
            }
            e.printStackTrace();
            strResult = "-1";
            handler.sendEmptyMessage(6);
//            Log.i("post","网络连接失败");
            try {
                httpRequest.clone();
                Runtime.getRuntime().gc();
            } catch (CloneNotSupportedException z) {
                z.printStackTrace();
            }
        }


    }

    static Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    httpinfces.setResData(strResult);
//                    runnUtils.interrupt();
                    runnUtils = null;
                    Runtime.getRuntime().gc();
                    break;
                case 2:
                    httpInface.setResData(result);
                    break;
                case 3:
                    httpInface.shibai(result);
                    break;
                case 6:
                    httpinfces.shibai(strResult);
                    break;
            }
        }
    };

    /**
     *  url 你请求的接口
     *  httpInfaces 回调对象
     */
    static  HttpInface httpInface;
    public static  void httpGET(String url, HttpInface httpInfaces){
        httpInface = httpInfaces;
        final String serverURL =url;
        new Thread(new Runnable() {
            @Override
            public void run() {


        HttpGet httpRequest = new HttpGet(serverURL);// 建立http get联机
        HttpResponse httpResponse = null;// 发出http请求
        try {



            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 60000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 60000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            httpResponse =  httpClient.execute(httpRequest);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                // 获取相应的字符串
                result = EntityUtils.toString(httpResponse.getEntity());
                handler.sendEmptyMessage(2);
                try {
                    httpRequest.clone();
                    httpClient = null;
                    Runtime.getRuntime().gc();
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }

            }else{
                result = "网络请求失败";
                handler.sendEmptyMessage(3);
                Log.i("zxxzxz",result+"1");
            }
        } catch(ConnectTimeoutException e){
            // 捕获超时异常 并反馈给调用者
            e.printStackTrace();
//            Toast.makeText(context,"网络状况不太好!",Toast.LENGTH_LONG).show();
            result = "网络请求失败";
            handler.sendEmptyMessage(3);
            Log.i("zxxzxz",result+"2");
        }catch (IOException e) {
            e.printStackTrace();
            result = "网络请求失败";
            handler.sendEmptyMessage(3);
            Log.i("zxxzxz",result+"3");
        }
            }
        }).start();

    }

}

2.图片上传

 2.1基于okhttp上传

package com.ax.okhttputils.okhttputils.utils;

import android.os.Handler;
import android.os.Message;

import com.ax.okhttputils.okhttputils.inface.HttpInface;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by HIAPAD on 2018/2/7.
 * function 上传图片
 *author 赵先森
 *
 */

public class UploadImageUtils {





    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    static HttpInface httpInfaces;
    private static String results;

    /**
     * 
     * @param url 请求地址
     * @param file 上传图片存放的路径
     * @param key 图片对应的key
     * @param httpInface 回调实例
     */
    public static void uploadImg(String url, File file, String key, HttpInface httpInface) {
        httpInfaces = httpInface;
        final OkHttpClient client = new OkHttpClient();
        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        if (file!=null) {
            builder.addFormDataPart(key, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));

        }

        MultipartBody requestBody = builder.build();
        //构建请求
        final Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        client.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                results = "失败";
                handlers.sendEmptyMessage(1);
//                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                results = response.body().string();
                handlers.sendEmptyMessage(1);
//                System.out.println("上传照片成功:response = " + response.body().string());


            }
        });

    }
    static Handler handlers = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    httpInfaces.setResData(results);
                    break;
            }
        }
    };

}

2.2 from表单上传

package com.ax.okhttputils.okhttputils.utils;

import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;


public class HttpRequester {
    private static final int TIME_OUT = 10*1000;
    private static final String BOUNDARY = "-------45962402127348";
    private static final String FILE_ENCTYPE = "multipart/form-data";
    private static final String CHARSET = "utf-8";
    static String key;
    public static InputStream post(String urlStr, Map<String, String> params,
                                   Map<String, File> images) {
        InputStream is = null;

        try {
            URL url = new URL(urlStr);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setConnectTimeout(5000);
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("Connection", "Keep-Alive");
            con.setRequestProperty("Charset", "UTF-8");
            con.setRequestProperty("Content-Type", FILE_ENCTYPE + "; boundary="
                    + BOUNDARY);

            StringBuilder sb = null;
            DataOutputStream dos = new DataOutputStream(con.getOutputStream());;
            if (params != null) {
                sb = new StringBuilder();
                for (String s : params.keySet()) {
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\""+key+"\"");
                    sb.append(s);
                    sb.append("\"\r\n\r\n");
                    sb.append(params.get(s));
                    sb.append("\r\n");
                }

                dos.write(sb.toString().getBytes());
            }

            if (images != null) {
                for (String s : images.keySet()) {
                    File f = images.get(s);
                    sb = new StringBuilder();
                    sb.append("--");
                    sb.append(BOUNDARY);
                    sb.append("\r\n");
                    sb.append("Content-Disposition: form-data; name=\"");
                    sb.append(s);
                    sb.append("\"; filename=\"");
                    sb.append(f.getName());
                    sb.append("\"\r\n");
                    sb.append("Content-Type: image/jpeg");//这里注意!如果上传的不是图片,要在这里改文件格式,比如txt文件,这里应该是text/plain
                    sb.append("\r\n\r\n");
                    dos.write(sb.toString().getBytes());

                    FileInputStream fis = new FileInputStream(f);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, len);
                    }
                    dos.write("\r\n".getBytes());
                    fis.close();
                }

                sb = new StringBuilder();
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("--\r\n");
                dos.write(sb.toString().getBytes());
            }
            dos.flush();

            if (con.getResponseCode() == 200)
                is = con.getInputStream();

            dos.close();
//            con.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }

    public static byte[] read(InputStream inStream) throws Exception{
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len = inStream.read(buffer)) != -1){
            outputStream.write(buffer, 0, len);
        }
        inStream.close();
        return outputStream.toByteArray();
    }

    public void ysing(File file){
        String sdStatus = Environment.getExternalStorageState();



    }

    /**
     * 
     * @param file 图片存放路径
     * @param RequestURL 上传地址
     * @param param 参数
     * @param keyzz 图片对应的key
     * @return
     */
    public static String uploadFile(File file, String RequestURL, Map<String, String> param,String keyzz){

        key = keyzz;
        String result = null;
        String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
        String PREFIX = "--" , LINE_END = "\r\n";
        String CONTENT_TYPE = "multipart/form-data";   //内容类型
        //压缩图片
        // 显示进度框
//      showProgressDialog();
        try {
            URL url = new URL(RequestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);  //允许输入流
            conn.setDoOutput(true); //允许输出流
            conn.setUseCaches(false);  //不允许使用缓存
            conn.setRequestMethod("POST");  //请求方式
            conn.setRequestProperty("Charset", CHARSET);  //设置编码
            conn.setRequestProperty("connection", "keep-alive");
            conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
            if(file!=null){
                /**
                 * 当文件不为空,把文件包装并且上传
                 */
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
                StringBuffer sb = new StringBuffer();

                String params = "";

                if (param != null && param.size() > 0) {
                    Iterator<String> it = param.keySet().iterator();
                    while (it.hasNext()) {
                        sb = null;
                        sb = new StringBuffer();
                        String keys = it.next();
                        String value = param.get(keys);
                        Log.i("zzzz",keys+"...."+value);
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                        sb.append("Content-Disposition: form-data; name=\"").append(keys).append("\"").append(LINE_END).append(LINE_END);
                        sb.append(value).append(LINE_END);
                        params = sb.toString();
                        dos.write(params.getBytes());
//                      dos.flush();
                    }
                }
                sb = new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                /**
                 * 这里重点注意:
                 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
                 * filename是文件的名字,包含后缀名的   比如:abc.png
                 */

                sb.append("Content-Disposition: form-data; name=\""+keyzz+"\";filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type: image/pjpeg; charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is = new FileInputStream(file);
                byte[] bytes = new byte[1024];
                int len = 0;
                while((len=is.read(bytes))!=-1){
                    dos.write(bytes, 0, len);

                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);

                dos.flush();
                /**
                 * 获取响应码  200=成功
                 * 当响应成功,获取响应的流
                 */

                int res = conn.getResponseCode();
                System.out.println("res========="+res);
                if(res==200){
                    InputStream input =  conn.getInputStream();
                    StringBuffer sb1= new StringBuffer();
                    int ss ;
                    while((ss=input.read())!=-1){
                        sb1.append((char)ss);
                    }
                    result = sb1.toString();
                    Log.i("pppp",result);
//                 // 移除进度框
//                  removeProgressDialog();

                }
                else{
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}

好了,就这样吧,有demo,大家可以点击下载!感觉该标注的都已经在代码的注释里说了,至于实现原理什么,大家又不懂的,咱们可以共同探讨!

下载地址:http://download.csdn.net/download/qq_34148178/10245456

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值