OKHttp post Stream (upload File with params)

 首先在项目的build.gradle中添加 okhttp 的引用

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'
    compile 'com.google.code.gson:gson:2.8.2'
    testCompile 'junit:junit:4.12'
}

然后构建一个 StreamHelper 的类

package com.asmpt.storeappservicetest;


import android.os.Environment;
import android.util.Log;


import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;


/**
 * Created by yuanxin on 1/30/2018.
 */

public class StreamHelper {
    public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return mediaType;
            }

            @Override
            public long contentLength() {
                try {
                    return inputStream.available();
                } catch (IOException e) {
                    return 0;
                }
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                Source source = null;
                try {
                    source = Okio.source(inputStream);
                    sink.writeAll(source);
                } finally {
                    Util.closeQuietly(source);
                }
            }
        };
    }

    public static void CreateFile(String content,String fileName) {
        File file = new File(Environment.getExternalStorageDirectory(),
                fileName);
        try {
            file.createNewFile();
            OutputStream os = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(os);
            DataOutputStream dos = new DataOutputStream(bos);
            byte[] body = content.getBytes("UTF-8");
            dos.write(body);
            dos.flush();
            dos.close();
        } catch (Exception e) {
            Log.d("WriteFile", e.getMessage());
        }

    }

    public static byte[] getPacket(String json, byte[] file) {
        byte[] jsonb = json.getBytes();
        int length = file.length + jsonb.length;
        Log.e("FileLength",file.length + "    " + jsonb.length);
        byte[] bytes = new byte[length + 1];
        byte[] lengthb = InttoByteArray(jsonb.length, 1);
        System.arraycopy(lengthb, 0, bytes, 0, 1);
        System.arraycopy(jsonb, 0, bytes, 1, jsonb.length);
        System.arraycopy(file, 0, bytes, 1 + jsonb.length, file.length);
        return bytes;
    }

    // 将int转换为字节数组
    public static byte[] InttoByteArray(int iSource, int iArrayLen) {
        byte[] bLocalArr = new byte[iArrayLen];
        for (int i = 0; (i < 4) && (i < iArrayLen); i++) {
            bLocalArr[i] = (byte) (iSource >> 8 * i & 0xFF);
        }
        return bLocalArr;
    }

    // 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位
    public static int BytestoInt(byte[] bRefArr) {
        int iOutcome = 0;
        byte bLoop;
        for (int i = 0; i < bRefArr.length; i++) {
            bLoop = bRefArr[i];
            iOutcome += (bLoop & 0xFF) << (8 * i);
        }
        return iOutcome;
    }


}

OKHttpHandle

package com.asmpt.storeappservicetest;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by yuanxin on 1/29/2018.
 */

public class OkHttpHandle {

    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/*;charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    public String post(String url,String json) throws IOException{
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    public String postStream(String url, File file, String parms) throws IOException{
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        if (parms != null) {
            builder.addFormDataPart("subject",parms);

        }


        if(file != null){

            RequestBody body = RequestBody.create(MediaType.parse("text/*"), file);

            builder.addFormDataPart("attach",file.getName(),body);
        }

        Request request = new Request.Builder().url(url).post(builder.build()).build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }


    public String postStream(String host,File file,JSONObject json) throws IOException{
        InputStream is = new FileInputStream(file);
        int len = 0;
        byte[] filebytes = new byte[(int) file.length()];
        while ((len = is.read(filebytes)) != -1 && len != 0){
            is.read(filebytes);
        }
        is.close();
        byte[] updata = StreamHelper.getPacket(json.toString(),filebytes);
        InputStream updateStream = new ByteArrayInputStream(updata);
        RequestBody requestBody = StreamHelper.create(MEDIA_TYPE_MARKDOWN,updateStream);
        Request request = new Request.Builder().url(host).post(requestBody).build();

        Response response = client.newCall(request).execute();



        return response.body().string();
    }



}

界面太简单就不写了,界面就一个button 和一个TextView 用来显示结果,

首先实例化一个OKHttpHandle 对象。
OkHttpHandle handle = new OkHttpHandle();

public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

上传数据类型为 (Json+File) 的情况的post方法

private void sendemail(){
        AsyncTask<Void,Void,String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {

                String params2 = "80028920:UpdateShelf";
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("subject",params2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                File myfile = new File(Environment.getExternalStorageDirectory() + "/attach.txt");
                String url = getString(R.string.url_email) + "SendEmailWithAttachment";
                try {
                    return handle.postStream(url,myfile,jsonObject);
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }


            }
            @Override
            protected void onPostExecute(String s){
                super.onPostExecute(s);
                if(null != s){
                    tv_result.setText(s);
                }
            }
        }.execute();
    }

上传数据类型为一个实体类CompositeType(没有附件)的情况的post方法

private void test(){
        AsyncTask<Void,Void,String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                String url = getString(R.string.url) + "GetDataUsingDataContract";
                CompositeType com = new CompositeType();
                com.setBoolValue(true);
                com.setStringValue("yuanxin");
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("composite",com);
                Gson gson = new Gson();

                String json = gson.toJson(map);
                OkHttpClient client = new OkHttpClient();

                RequestBody body = RequestBody.create(JSON,json);
                Request request = new Request.Builder().url(url).post(body).build();
                try {
                    Response response = client.newCall(request).execute();

                    JSONObject responseObj = new JSONObject(response.body().string());
                    String result = responseObj.getString("GetDataUsingDataContractResult").toString();
                    CompositeType com2 = gson.fromJson(result, new TypeToken<CompositeType>(){}.getType());
                    String test = "callback successful:\n" + "value:" + com2.isBoolValue() + "\nmsg:" + com2.getStringValue();
                    return test;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                }catch (JSONException e) {
                    e.printStackTrace();
                    return null;
                }

            }
            @Override
            protected void onPostExecute(String s){
                super.onPostExecute(s);
                if(null != s){
                    tv_result.setText(s);
                }
            }
        }.execute();
    }

CompositeType

public class CompositeType {
    private boolean BoolValue;
    private String StringValue;

    public boolean isBoolValue() {
        return BoolValue;
    }

    public void setBoolValue(boolean boolValue) {
        BoolValue = boolValue;
    }

    public String getStringValue() {
        return StringValue;
    }

    public void setStringValue(String stringValue) {
        StringValue = stringValue;
    }
}

猜你喜欢

转载自www.cnblogs.com/yx-android/p/9081783.html