1所需网络框架 Volley Base64编码
创建编码类
public class Base64{
public static String GetImageStr(Bitmap bitmap){
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,40,bos);//压缩图片
byte[] byte = bos.toByteArray();
return Base64.encodeToString(bytes,Base64.DEFAULT);.
}
}
上传 头像到服务器
private void uploadImageToServer(Bitmap bitmap){
String imagebase = Base64.GetImageStr(bitmap);
//上传头像需要唯一标示来识别你的头像,你也可以创建实体类,我这样是图方便。
Map<String,String> map = new HashMao<>();
map.put("id","你的唯一标示");
map.put("Image",imagebase);
JSONObject object = new JSONObject(map);
RequestQueue queue = Volley.newRequestQueue(this);//建议在application中创建
JsonObjectRequest request=new JsonObjectRequest(Post,"http://你的接口网址",new Response.Listener<JsonObject>(){
@Override
public void onResponse(JsonObject response){
//上传成功后的消息回调
//然后你可以发送广播去更新别的界面头像,但是你必须缓存一下头像地址
}
},
new ResponseError.Listener(){
@Override
public void onResponseError(VollerError error){
//错误处理
L.d("Error Message:","Error is"+error);
}
});
//防止网络超时,这里是设置5秒;
queue.setRetryPolicy(new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(request);
}