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            }        });


服务器端先创建文件,之后将获取的输入流转换为byte 数组,最后将数据写入文件
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




原创粉丝点击