Android 使用okhttp3 post 上传图片
来源:互联网 发布:阿里云域名备案多少钱 编辑:程序博客网 时间:2024/06/05 19:16
由于我做的系统需要Android端与数据库端交互数据,主要是一些文字与图片。文字的交互使用的是json和okhttp3 。因为我是新手,所以不会使用什么框架,就使用简单的流上传,在头部添加自定义的键值对以示区别。
完成这些也参考了一些其他的博客,会在最后列出
下面的代码是HttpUtil 中的上传的静态方法:
public static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png;charset=utf-8"); public static final OkHttpClient client = new OkHttpClient(); public static final String POST_FEEDBACK_BITMAP = "feed_back_post"; /** * 用于上传本地数据至服务器 * @param mediaType 上传数据类型 * @param data 为了保证可以传递各种类型的数据,传入的数据为byte[]类型 * @param url 目标服务器的url地址 * @param postType 用于在传送头部添加自定义信息,区别不同的提交请求 */ public static void postByOkHttp(final MediaType mediaType,final byte[] data, final String url , String postType) { RequestBody requestBody = new RequestBody() { @Override public MediaType contentType() { return mediaType; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(data); bufferedSink.flush(); bufferedSink.close(); } }; Request request = new Request.Builder() .url(url) .addHeader("post_type", postType) //添加自定义头部,标识上传类型 .post(requestBody) .build(); try{ Response response = client.newCall(request).execute(); if(!response.isSuccessful()) throw new IOException("传送发生错误!"+response); }catch (IOException e){ e.printStackTrace(); } }除了纯文本数据外,所有的数据传递均转换为byte数组,MediaType 是上传的类型,类似于web中的ContentType,如果上传其他类型的文件,类型参照http://tool.oschina.net/commons/
下面是定义的一个按钮的监听,picture 是xml 布局中的ImageView ,打开cache 可以获取其中的bitmap 图片
bUpload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { picture.setDrawingCacheEnabled(true); //打开drawing cache Bitmap bitmap = Bitmap.createBitmap(picture.getDrawingCache()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream); //将bitmap 压缩成png格式图像 bytearray = byteArrayOutputStream.toByteArray(); //尝试直接使用本地的png图片上传,排除问题点 /* final Drawable drawable = getResources().getDrawable(R.drawable.start);*/ // int bytes = bitmap.getByteCount(); //获取bitmap的字节数 // ByteBuffer byteBuffer = ByteBuffer.allocate(bytes); // bitmap.copyPixelsToBuffer(byteBuffer); //将bitmap 拷贝到bytebuffer /* try{ 测试成功代码 final byte[] dt = drawable.toString().getBytes("utf-8"); //将byteBuffer转换为byte[] BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); picture.setImageBitmap(bitmap); bitmap.compress(Bitmap.CompressFormat.PNG,100,byteArrayOutputStream); bytearray = byteArrayOutputStream.toByteArray(); Log.d("bytearry:",new String(bytearray)); }catch (UnsupportedEncodingException e){ e.printStackTrace(); }*/ //在 新线程中上传数据 new Thread(new Runnable() { @Override public void run() { HttpUtil.postByOkHttp(HttpUtil.MEDIA_TYPE_PNG,bytearray, "http://192.168.1.111:8080/JsonAndroid/factories/MaterialFacServlet" ,HttpUtil.POST_FEEDBACK_BITMAP); } }).start(); picture.setDrawingCacheEnabled(false); //关闭drawing cache } });
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//获取android 客户端上传的数据//数据类型等判断根据header中的post_type判断System.out.println("Post 正在执行。。。。");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");final String getPostType = request.getHeader("post_type");System.out.println("getposttype: " + getPostType);if(getPostType != null && getPostType.equals("feed_back_post")){InputStream input = request.getInputStream();//获取请求体的数据File file = null;file = new File(request.getServletContext().getRealPath("/")+"images\\bitmap.png");if(!file.exists())file.createNewFile();BufferedOutputStream bufferout = null;FileOutputStream out = new FileOutputStream(file);//文件输出流byte[] data = new byte[10240];int len=0;StringBuffer strbuf = new StringBuffer();bufferout = new BufferedOutputStream(out);while((len = input.read(data)) != -1){//strbuf.append((new String(data,0,len)));bufferout.write(data, 0, len);}System.out.println("data is: " + new String(data));if(bufferout != null)bufferout.close();if(out != null)out.close();if(input != null)input.close();
参考博客:
http://blog.csdn.net/lmj623565791/article/details/47911083
http://ask.csdn.net/questions/151958
http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0106/2275.html
http://www.cnblogs.com/psklf/p/5889978.html
阅读全文
0 0
- Android 使用okhttp3 post 上传图片
- android okHttp3 post上传图片给服务器
- android okhttp3使用base64字符串上传图片问题
- Android OkHttp3 上传多张图片
- okhttp3上传图片
- 使用OKHttp3 get请求 , post请求 , 多文件上传 , 包看包会
- 使用OKHttp3 get请求 , post请求 , 多文件上传 , 包看包会
- android okhttp3中设置请求头以及上传图片
- ios 使用post上传图片
- Android使用post方式上传图片到服务器的方法
- Android使用post方式上传图片到服务器的方法
- Android OKhttp3使用
- android okhttp3框架使用
- Android 通过HTTP POST 上传图片文件
- Android 通过HTTP POST 上传图片文件
- Android 通过HTTP POST 上传图片文件
- android上传图片以及POST字符串
- 使用AFNetworking图片上传post带参数
- 深圳开发无人超市系统招商加盟的条件
- 使用Python和BeautifulSoup爬取历史上的今天网站并将描述及网址存储到csv文件中
- Qt-解锁QtPropertyBrowser控件
- 浅谈dom事件
- Integer与int的种种比较你知道多少?
- Android 使用okhttp3 post 上传图片
- 暗黑破坏神(DIABLOII 1.11B)BOT下载
- 项目管理——进度
- 应用缓存初级使用指南
- ANDREW Ng教授的机器学习(Machine Learning)学习笔记(1)– 认识机器学习
- 检查网络是否可用
- Exists 与 Count(*) 效率比较
- GAMIT错误i提示:Only one or no existing X-files
- 我为什么不在北京买房?