MainActivity

package com.bwie.lianxi1;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.ActionMode;
import android.view.View; import okhttp3.Cache;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;
import okhttp3.CacheControl;
import okhttp3.Callback;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.bt).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toPhoto();
}
});
findViewById(R.id.bt2).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toCamera();
}
});
cache();
}
public void synchronousMethod(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build(); Call call = client.newCall(request);
//同步
Response response = call.execute() ;
if(response.isSuccessful()){
ResponseBody body = response.body() ;
String result = body.string() ;
System.out.println("result = " + result);
} } catch (IOException e) {
e.printStackTrace();
} }
}).start(); }
public void asynchronousGet(){
// http://www.baidu.com/aaaa/
// http://www.baidu1.com/aaaa/
// http://www.baidu.com/aaaa/ // http://www.baidu2.com/aaaa/
try {
OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.header("key","value")
.header("key","value1")
.addHeader("Connection","Keep-Alive")
.addHeader("Connection","Keep-Alive1")
.build();
Call call = client.newCall(request); call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException { String result = response.body().string() ;
System.out.println("result = " + result); }
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static final MediaType MEDIA_TYPE_MARKDOWN=MediaType.parse("text/x-markdown; charset=utf-8");
public void postString(){
new Thread(new Runnable() {
@Override
public void run() {
try {
File file = new File("本地图片路径");
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN,file)).build();
Response response = client.newCall(request).execute();
if(response.isSuccessful()){
String result = response.body().string() ;
System.out.println("result = " + result); } } catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
public void postFile(File file){ // sdcard/dliao/aaa.jpg
String path = file.getAbsolutePath() ;
String [] split = path.split("\\/");
MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
// file
.addFormDataPart("imageFileName",split[split.length-])
.addFormDataPart("image",split[split.length-],RequestBody.create(MEDIA_TYPE_PNG,file))
.build(); Request request = new Request.Builder().post(requestBody).url("http://qhb.2dyt.com/Bwei/upload").build(); client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) { } @Override
public void onResponse(Call call, Response response) throws IOException { System.out.println("response = " + response.body().string()); }
}); } static final int INTENTFORCAMERA = ;
static final int INTENTFORPHOTO = ;
public String LocalPhotoName;
public String createLocalPhotoName() {
LocalPhotoName = System.currentTimeMillis() + "face.jpg";
return LocalPhotoName ;
}
public void toCamera(){
try {
Intent intentNow = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = null ;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //针对Android7.0,需要通过FileProvider封装过的路径,提供给外部调用
// uri = FileProvider.getUriForFile(UploadPhotoActivity.this, "com.bw.dliao", SDCardUtils.getMyFaceFile(createLocalPhotoName()));//通过FileProvider创建一个content类型的Uri,进行封装
// }else {
uri = Uri.fromFile(SDCardUtils.getMyFaceFile(createLocalPhotoName())) ;
// }
intentNow.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intentNow, INTENTFORCAMERA);
} catch (Exception e) {
e.printStackTrace();
}
} /**
360 * 打开相册
361 */
public void toPhoto() {
try {
createLocalPhotoName();
Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
getAlbum.setType("image/*");
startActivityForResult(getAlbum, INTENTFORPHOTO);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data); switch (requestCode) {
case INTENTFORPHOTO:
//相册
try {
// 必须这样处理,不然在4.4.2手机上会出问题
Uri originalUri = data.getData();
File f = null;
if (originalUri != null) {
f = new File(SDCardUtils.photoCacheDir, LocalPhotoName);
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = this.getContentResolver().query(originalUri, proj, null, null, null);
if (null == actualimagecursor) {
if (originalUri.toString().startsWith("file:")) {
File file = new File(originalUri.toString().substring(, originalUri.toString().length()));
if(!file.exists()){
//地址包含中文编码的地址做utf-8编码
originalUri = Uri.parse(URLDecoder.decode(originalUri.toString(),"UTF-8"));
file = new File(originalUri.toString().substring(, originalUri.toString().length()));
}
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(f);
copyStream(inputStream, outputStream);
}
} else {
// 系统图库
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor.getString(actual_image_column_index);
if (img_path == null) {
InputStream inputStream = this.getContentResolver().openInputStream(originalUri);
FileOutputStream outputStream = new FileOutputStream(f);
copyStream(inputStream, outputStream);
} else {
File file = new File(img_path);
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(f);
copyStream(inputStream, outputStream);
}
}
Bitmap bitmap = ImageResizeUtils.resizeImage(f.getAbsolutePath(), );
int width = bitmap.getWidth();
int height = bitmap.getHeight();
FileOutputStream fos = new FileOutputStream(f.getAbsolutePath());
if (bitmap != null) { if (bitmap.compress(Bitmap.CompressFormat.JPEG, , fos)) {
fos.close();
fos.flush();
}
if (!bitmap.isRecycled()) {
bitmap.isRecycled();
} System.out.println("f = " + f.length());
postFile(f); } }
} catch (Exception e) {
e.printStackTrace(); } break;
case INTENTFORCAMERA:
// 相机
try {
//file 就是拍照完 得到的原始照片
File file = new File(SDCardUtils.photoCacheDir, LocalPhotoName);
Bitmap bitmap = ImageResizeUtils.resizeImage(file.getAbsolutePath(), );
int width = bitmap.getWidth();
int height = bitmap.getHeight();
FileOutputStream fos = new FileOutputStream(file.getAbsolutePath());
if (bitmap != null) {
if (bitmap.compress(Bitmap.CompressFormat.JPEG, , fos)) {
fos.close();
fos.flush();
}
if (!bitmap.isRecycled()) {
//通知系统 回收bitmap
bitmap.isRecycled();
}
System.out.println("f = " + file.length()); postFile(file);
}
} catch (Exception e) {
e.printStackTrace();
} break;
} }
public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception {
try {
byte[] buffer = new byte[];
int len = ;
while ((len = inputStream.read(buffer)) != -) {
outStream.write(buffer, , len);
}
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
inputStream.close();
}
if(outStream != null){
outStream.close();
}
} } public void post(){ OkHttpClient client = new OkHttpClient(); RequestBody requestBody = new FormBody.Builder()
.add("username","1507D")
.add("password","1507D")
.add("postkey","")
.build(); Request request = new Request.Builder().url("http://qhb.2dyt.com/Bwei/login")
.post(requestBody).build(); client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) { } @Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("response = " + response.body().string());
}
}); } public void cache(){ new Thread(new Runnable() {
@Override
public void run() {
try {
int cacheSize = * * ; // 10 MiB
Cache cache = new Cache(getCacheDir(), cacheSize);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.cache(cache)
.build();
Request request = new Request.Builder()
.cacheControl(CacheControl.FORCE_NETWORK)
.url("http://publicobject.com/helloworld.txt")
.build();
String response1Body;
Response response1 = client.newCall(request).execute();
// () {
if (!response1.isSuccessful()) throw new IOException("Unexpected code " + response1);
response1Body = response1.body().string();
System.out.println("Response 1 response: " + response1);
System.out.println("Response 1 cache response: " + response1.cacheResponse());
System.out.println("Response 1 network response: " + response1.networkResponse());
// }
String response2Body;
//
// {
// Response response2 = client.newCall(request).execute();
//
//
//// Call call1 = client.newCall(request);
////
//// call1.cancel();
//
// if (!response2.isSuccessful()) throw new IOException("Unexpected code " + response2);
//
// response2Body = response2.body().string();
// System.out.println("Response 2 response: " + response2);
// System.out.println("Response 2 cache response: " + response2.cacheResponse());
// System.out.println("Response 2 network response: " + response2.networkResponse());
//
//
// System.out.println("Response 2 equals Response 1? " + response1Body.equals(response2Body));
//
}catch (Exception e) {
}
}
}).start();
}
//
public void percall(){
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(, TimeUnit.SECONDS).build();
OkHttpClient client1 = client.newBuilder().connectTimeout(, TimeUnit.SECONDS).build();
OkHttpClient client2 = client.newBuilder().connectTimeout(, TimeUnit.SECONDS).build();
// client.newCall()
}
}
LoggingInterceptor
package com.bwie.lianxi1;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response; class LoggingInterceptor implements Interceptor {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request(); long t1 = System.currentTimeMillis(); Response response = chain.proceed(request); long t2 = System.currentTimeMillis(); System.out.println("t2 = " +( t2-t1)); return response;
}
}
ImageResizeUtils
package com.bwie.lianxi1;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import static android.graphics.BitmapFactory.decodeFile; /**
* Created by muhanxi on 17/7/6.
*/ public class ImageResizeUtils { /**
* 照片路径
* 压缩后 宽度的尺寸
* @param path
* @param specifiedWidth
*/
public static Bitmap resizeImage(String path, int specifiedWidth) throws Exception { Bitmap bitmap = null;
FileInputStream inStream = null;
File f = new File(path);
System.out.println(path);
if (!f.exists()) {
throw new FileNotFoundException();
}
try {
inStream = new FileInputStream(f);
int degree = readPictureDegree(path);
BitmapFactory.Options opt = new BitmapFactory.Options();
//照片不加载到内存 只能读取照片边框信息
opt.inJustDecodeBounds = true;
// 获取这个图片的宽和高
decodeFile(path, opt); // 此时返回bm为空 int inSampleSize = 1;
final int width = opt.outWidth;
// width 照片的原始宽度 specifiedWidth 需要压缩的宽度
// 1000 980
if (width > specifiedWidth) {
inSampleSize = (int) (width / (float) specifiedWidth);
}
// 按照 565 来采样 一个像素占用2个字节
opt.inPreferredConfig = Bitmap.Config.RGB_565;
// 图片加载到内存
opt.inJustDecodeBounds = false;
// 等比采样
opt.inSampleSize = inSampleSize;
// opt.inPurgeable = true;
// 容易导致内存溢出
bitmap = BitmapFactory.decodeStream(inStream, null, opt);
// bitmap = BitmapFactory.decodeFile(path, opt);
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
inStream = null;
}
} if (bitmap == null) {
return null;
}
Matrix m = new Matrix();
if (degree != 0) {
//给Matrix 设置旋转的角度
m.setRotate(degree);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
}
float scaleValue = (float) specifiedWidth / bitmap.getWidth();
// 等比压缩
m.setScale(scaleValue, scaleValue);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
return bitmap;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} } /**
* 读取图片属性:旋转的角度
*
* @param path 源信息
* 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
} public static void copyStream(InputStream inputStream, OutputStream outStream) throws Exception {
try {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream != null){
inputStream.close();
}
if(outStream != null){
outStream.close();
}
} } }
SDCardUtils
package com.bwie.lianxi1;

import android.os.Environment;
import android.os.StatFs; import java.io.File;
import java.io.IOException; public class SDCardUtils { public static final String DLIAO = "dliao" ; public static File photoCacheDir = SDCardUtils.createCacheDir(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + DLIAO);
public static String cacheFileName = "myphototemp.jpg"; public static boolean isSDCardExist() {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return true;
} else {
return false;
}
} public static void delFolder(String folderPath) {
try {
delAllFile(folderPath);
String filePath = folderPath;
filePath = filePath.toString();
File myFilePath = new File(filePath);
myFilePath.delete();
} catch (Exception e) {
e.printStackTrace();
}
} public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = ; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
delFolder(path + "/" + tempList[i]);// 再删除空文件夹
flag = true;
}
}
return flag;
} public static boolean deleteOldAllFile(final String path) {
try {
new Thread(new Runnable() { @Override
public void run() {
delAllFile(Environment.getExternalStorageDirectory() + File.separator + DLIAO);
}
}).start(); } catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
} /**
* 给定字符串获取文件夹
*
* @param dirPath
* @return 创建的文件夹的完整路径
*/
public static File createCacheDir(String dirPath) {
File dir = new File(dirPath);;
if(isSDCardExist()){
if (!dir.exists()) {
dir.mkdirs();
}
}
return dir;
} public static File createNewFile(File dir, String fileName) {
File f = new File(dir, fileName);
try {
// 出现过目录不存在的情况,重新创建
if (!dir.exists()) {
dir.mkdirs();
}
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return f;
} public static File getCacheFile() {
return createNewFile(photoCacheDir, cacheFileName);
} public static File getMyFaceFile(String fileName) {
return createNewFile(photoCacheDir, fileName);
} /**
* 获取SDCARD剩余存储空间
*
* @return 0 sd已被挂载占用 1 sd卡内存不足 2 sd可用
*/
public static int getAvailableExternalStorageSize() {
if (isSDCardExist()) {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
long memorySize = availableBlocks * blockSize;
if(memorySize < **){
return ;
}else{
return ;
}
} else {
return ;
}
}
}

权限

  <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
												

okhttp 调用相机 上传服务器的更多相关文章

  1. mui调用本地相册调用相机上传照片

    调用mui的常用库和jquery html部分: <header class="mui-bar mui-bar-nav"> <a class="mui- ...

  2. HTML5调用本地摄像头画面,拍照,上传服务器

    实现功能和适用业务 采集本地摄像头获取摄像头画面,拍照保存,上传服务器: 前端上传图片处理,展示,缩小,裁剪,上传服务器 实现步骤 调取本地摄像头(getUserMedia)/上传图片,将图片/视频显 ...

  3. ios-高德、百度后台定位并上传服务器

    一.配置高德或百度的后台定位框架和代码(略). 二.配置app不被系统kill,定时获取地理位置信息,并上传服务器(AppDelegate里面). 具体代码: 1. - (void)applicati ...

  4. HTTP文件上传服务器-支持超大文件HTTP断点续传的实现办法

    最近由于笔者所在的研发集团产品需要,需要支持高性能的大文件http上传,并且要求支持http断点续传.笔者在以前的博客如何实现支持大文件的高性能HTTP文件上传服务器已经介绍了实现大文件上传的一些基本 ...

  5. Linux 本地文件或文件夹上传服务器

    Linux 本地文件或文件夹上传服务器 一.权限设置 本地文件或文件夹上传服务器,你首先需要获取到root权限: 二.上传方式 上传方式有两种 : 1.通过 FTP 客户端上传文件或文件夹: 2.通过 ...

  6. IOS 视频.图片上传服务器

    //上传视频 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];    manager.requestSerializer. ...

  7. vue代码上传服务器后背景图片404解决方法

    问题:代码上传服务器后,图片404,使用的font-awesome图标也是404 解决办法: 如果你用了vue-cil,那么在build目录下找到utils.js中的ExtractTextPlugin ...

  8. eclipse导出文件上传服务器

    [1]导出     选择项目    文件导出 输入导出路径如f盘ftp文件夹下 [2]利用scr上传服务器工具 上传到 home/tomcat/app/项目名称/ 不导入upload文件 [待完善]

  9. Shell脚本调用ftp上传文件

    Shell脚本调用ftp上传文件 1.脚本如下 ftp -n<<! open x.x.x.x ###x.x.x.x为ftp地址 user username password ###user ...

随机推荐

  1. 用Jedis调用Lua脚本来完成redis的数据操作

    1.先完成一个简单的set/get操作 package com.example.HnadleTaskQueue; import redis.clients.jedis.Jedis; import ja ...

  2. 十六进制颜色值和rgb颜色值互相转换

    在之前的一篇文章<将16进制的颜色转为rgb颜色>中,曾经写过将16进制的颜色转换为rgb颜色. 当然了,今天再看,还是有很多可以优化的地方,所以对之前的代码重构了一遍,并且同时写了一个反 ...

  3. 【Linux】【GIt】Linux下安装和配置Git(转)

    yum安装 这里采用的是CentOS系统,如果采用yum安装git的方式: yum install git 很快就okay了,但是这里遇到一个问题.: 在网上搜寻了原因,说是要安装: yum inst ...

  4. C++ #define #if #ifndef 宏指令

    不会用就直接复制粘贴 #define CURSOR(top,bottom) (((top)<<8)|(bottom)) #define mul(x1,x2) (x1*x2) #define ...

  5. leetcode76

    class Solution: def minWindow(self, s: str, t: str) -> str: n = len(s) if n==0: return "&quo ...

  6. vagrant 同时设置多个同步目录

    修改Vagrantfile文件 如下所示 config.vm.synced_folder "./", "/var/www/pyxis2", owner: &qu ...

  7. Java POI操作Excel注意点

    excel的行索引和列索引都是从0开始,而行号和列号都是从1开始 POI·操作excel基本上都是使用索引 XSSFRow对象的 row.getLastCellNum() 方法返回的是当前行最后有效列 ...

  8. grains和pillar的联合使用

    在编写sls文件的时候,对于不同的客户端,在配置管理的时候,其安装的环境,配置文件和启动的服务都相同: 如果完全是不同的环境,建议写单独的sls文件,不要混合在一起; 如果是相同的环境,只不过对于不同 ...

  9. css之标签选择器

    标签(空格分隔): 标签选择器 选择器定义: 在一个HTML页面中会有很多很多的元素,不同的元素可能会有不同的样式,某些元素又需要设置相同的样式,选择器就是用来从HTML页面中查找特定元素的,找到元素 ...

  10. 迭代器模块 itertools

    无限迭代器 itertools 包自带了三个可以无限迭代的迭代器.这意味着,当你使用他们时,你要知道你需要的到底是最终会停止的迭代器,还是需要无限地迭代下去. 这些无限迭代器在生成数字或者在长度未知的 ...