与服务器的通讯框架

package com.arcsoft.sdk_demo;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Base64;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class SelfHttpRequest {
    private Boolean success;
    private Boolean wait;
    private UserInfo userInfo;
    private StringBuffer log;

    public SelfHttpRequest() {
        success = false;
        wait = false;
        userInfo = new UserInfo();
        log = new StringBuffer();
    }

    public Boolean getWait() {
        return wait;
    }

    public void setWait(Boolean wait) {
        this.wait = wait;
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    /*
     * 请求操作
     * */
    public void requestForResult(Bitmap bmp){
        //toBase64
        String s = "";
        s = bitmapToBase64(bmp);
        //请求服务器
        try {
            doHttpPostJSON(s);
        } catch (Exception e) {
            Log.e("http",e.toString());
        }
    }

    /*
     * bitmap转base64
     * */
    private static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /*end*/


    /*
     * 向服务器发送数据
     * */
    private void doHttpPostJSON(final String sbmp){
        new Thread() {
            @Override
            public void run() {
                try {
                    //定义一个JSON,用于向服务器提交数据
                    JSONObject jsonObj = new JSONObject();
                    jsonObj.put("image", sbmp + "");
//                            .put("clientid", "123456")
//                            .put("type", "face")
//                            .put("action",machineType+"");
                    String jsonString = jsonObj.toString();

                    String url = "https://web.huafeisoft.cn/webservice/sendFaceInfo.do";
                    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setRequestMethod("POST");
                    connection.setDoOutput(true);
                    connection.setRequestProperty("User-Agent", "Fiddler");
                    connection.setRequestProperty("Content-Type", "application/json");
                    connection.setRequestProperty("Charset", "UTF-8");
                    OutputStream os = connection.getOutputStream();
                    os.write(jsonString.getBytes());
                    os.close();
                    /*
                     * 等待返回结果
                     * */
                    String s = convertStreamToString(connection.getInputStream());
//                    Log.i("success", "成功" + s);
                    setSuccessInfo(s);
//                    writeToLoacl(s);
                } catch (Exception e) {

                }
            }
        }.start();
    }

    /*
     * 截取服务器success信息
     * */
    private void setSuccessInfo(String streamin){
        try {
            //解析JSON
            JSONObject jsonObject = new JSONObject(streamin);
            userInfo.setSuccess(jsonObject.getString("msg"));
//            userInfo.setName(jsonObject.getString("name"));
//            userInfo.setTime(jsonObject.getString("time"));
            Log.i("success","msg:"+userInfo.getSuccess());
            //设置成功量
            if (userInfo.getSuccess().equals("success")){
                success = true;
            }else {
                success = false;
            }
        }catch (Exception e){
            Log.i("success",e.toString());
        }
        //设置等待量
        wait = false;
    }

    /*
     * InputStreamTOString
     * */
    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    /*
     * writeToLocal
     * */
    private void writeToLoacl(String s) {
        String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        File saveFile = new File(sdCardDir, "记录.txt");
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日    HH:mm:ss", Locale.getDefault());
        String time = formatter.format(new Date(System.currentTimeMillis()));
        try {
            FileOutputStream outStream = new FileOutputStream(saveFile);
            byte[] bytes = s.getBytes();
            outStream.write(bytes);
            outStream.close();
        } catch (Exception e) {

        }
        Log.i("write", "成功");
    }
}

猜你喜欢

转载自www.cnblogs.com/Mr-quin/p/9134391.html