OKHttp上传文件,如何获取返回的结果

发布于 2022-09-02 15:57:05 字数 1261 浏览 21 评论 0

1.以前我用volley框架上传文件的时候可以直接获取到返回的结果。
2.现在换了Okhttp之后,都不知道返回的结果在哪里
返回结果:
方法一


        try {
            Response response =  call.execute();
            String result = response.body().string();
            if(response.isSuccessful()){
                listener.onUploadSuccess(result);
            }else{
                listener.onUploadFail();
            }

            
        } catch (IOException e) {
            e.printStackTrace();
        }

方法二
`call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {

            Log.e("upload", "上传失败" + e.toString());
            e.printStackTrace();
            removeRequest(tag);
            listener.onUploadFail();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try { 
                Log.e("upload", "上传请求成功" + response.body().string());
                listener.onUploadSuccess(response.body().string());
                removeRequest(tag);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            }

        }
    });

`
以上方法都不行~求大神解救

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挽清梦 2022-09-09 15:57:05

volley 你是怎么上传的,求解答

贵在坚持 2022-09-09 15:57:05

import android.text.TextUtils; 
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader; 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

/**
 * Created by ares on 15/12/14.
 */
public class UploadFileEntity implements HttpEntity {


    private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
            .toCharArray();
    /**
     * 换行符
     */
    private final String NEW_LINE_STR = "\r\n";
    private final String CONTENT_TYPE = "Content-Type: ";
    private final String CONTENT_DISPOSITION = "Content-Disposition: ";
    /**
     * 文本参数和字符集
     */
    private final String TYPE_TEXT_CHARSET = "text/plain; charset=UTF-8";

    /**
     * 字节流参数
     */
    private final String TYPE_OCTET_STREAM = "application/octet-stream";
    /**
     * 二进制参数
     */
    private final byte[] BINARY_ENCODING = "Content-Transfer-Encoding: binary\r\n\r\n".getBytes();
    /**
     * 文本参数
     */
    private final byte[] BIT_ENCODING = "Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes();

    /**
     * 分隔符
     */
    private String mBoundary = null;
    /**
     * 输出流
     */
    ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream();

    public UploadFileEntity() {
        this.mBoundary = generateBoundary();
    }

    /**
     * 生成分隔符
     *
     * @return
     */
    private final String generateBoundary() {
        final StringBuffer buf = new StringBuffer();
        final Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        return buf.toString();
    }

    /**
     * 参数开头的分隔符
     *
     * @throws IOException
     */
    private void writeFirstBoundary() throws IOException {
        mOutputStream.write(("--" + mBoundary + "\r\n").getBytes());
    }

    /**
     * 添加文本参数
     *
     * @param value
     */
    public void addStringPart(final String paramName, final String value) {
        writeToOutputStream(paramName, value.getBytes(), TYPE_TEXT_CHARSET, BIT_ENCODING, "");
    }

    /**
     * 将数据写入到输出流中
     *
     * @param rawData
     * @param type
     * @param encodingBytes
     * @param fileName
     */
    private void writeToOutputStream(String paramName, byte[] rawData, String type,
                                     byte[] encodingBytes,
                                     String fileName) {
        try {
            writeFirstBoundary();
            mOutputStream.write((CONTENT_TYPE + type + NEW_LINE_STR).getBytes());
            mOutputStream
                    .write(getContentDispositionBytes(paramName, fileName));
            mOutputStream.write(encodingBytes);
            mOutputStream.write(rawData);
            mOutputStream.write(NEW_LINE_STR.getBytes());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加二进制参数, 例如Bitmap的字节流参数
     *
     * @param rawData
     */
    public void addBinaryPart(String paramName, final byte[] rawData) {
        writeToOutputStream(paramName, rawData, TYPE_OCTET_STREAM, BINARY_ENCODING, "no-file");
    }

    /**
     * 添加文件参数,可以实现文件上传功能
     *
     * @param key
     * @param file
     */
    public void addFilePart(final String key, final File file) {
        InputStream fin = null;
        try {
            fin = new FileInputStream(file);
            writeFirstBoundary();
            final String type = CONTENT_TYPE + TYPE_OCTET_STREAM + NEW_LINE_STR;
            mOutputStream.write(getContentDispositionBytes(key, file.getName()));
            mOutputStream.write(type.getBytes());
            mOutputStream.write(BINARY_ENCODING);

            final byte[] tmp = new byte[4096];
            int len = 0;
            while ((len = fin.read(tmp)) != -1) {
                mOutputStream.write(tmp, 0, len);
            }
            mOutputStream.flush();
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            closeSilently(fin);
        }
    }

    private void closeSilently(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    private byte[] getContentDispositionBytes(String paramName, String fileName) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(CONTENT_DISPOSITION + "form-data; name=\"" + paramName + "\"");
        // 文本参数没有filename参数,设置为空即可
        if (!TextUtils.isEmpty(fileName)) {
            stringBuilder.append("; filename=\""
                    + fileName + "\"");
        }

        return stringBuilder.append(NEW_LINE_STR).toString().getBytes();
    }

    @Override
    public long getContentLength() {
        return mOutputStream.toByteArray().length;
    }

    @Override
    public Header getContentType() {
        return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + mBoundary);
    }

    @Override
    public boolean isChunked() {
        return false;
    }

    @Override
    public boolean isRepeatable() {
        return false;
    }

    @Override
    public boolean isStreaming() {
        return false;
    }

    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        // 参数最末尾的结束符
        final String endString = "--" + mBoundary + "--\r\n";
        // 写入结束符
        mOutputStream.write(endString.getBytes());
        //
        outstream.write(mOutputStream.toByteArray());
    }

    @Override
    public Header getContentEncoding() {
        return null;
    }

    @Override
    public void consumeContent() throws IOException,
            UnsupportedOperationException {
        if (isStreaming()) {
            throw new UnsupportedOperationException(
                    "Streaming entity does not implement #consumeContent()");
        }
    }

    @Override
    public InputStream getContent() {
        return new ByteArrayInputStream(mOutputStream.toByteArray());
    }


}

 


package com.kit.reporterdd.utils.UploadFile;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.Response.ErrorListener;
import com.android.volley.toolbox.HttpHeaderParser;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class UploadFileRequest extends Request<String> {

UploadFileEntity mMultiPartEntity = new UploadFileEntity();

Map<String, String> mHeaders = new HashMap<String, String>();

private final Listener<String> mListener;

/**
    • Creates a new request with the given url.
      *

    • @param url URL to fetch the string at

    • @param listener Listener to receive the String response
      */

    1. UploadFileRequest(String url, Listener<String> listener) {

         this(url, listener, null);

      }

      /**

      • Creates a new POST request.
        *

      • @param url URL to fetch the string at

      • @param listener Listener to receive the String response

      • @param errorListener Error listener, or null to ignore errors
        */

    2. UploadFileRequest(String url, Listener<String> listener, ErrorListener errorListener) {

         super(Method.POST, url, errorListener);
         mListener = listener;

      }

      /**

      • @return
        */

    3. UploadFileEntity getMultiPartEntity() {

         return mMultiPartEntity;

      }

      @Override

    4. String getBodyContentType() {

         return mMultiPartEntity.getContentType().getValue();

      }

    5. void addHeader(String key, String value) {

         mHeaders.put(key, value);

      }

      @Override

    6. Map<String, String> getHeaders() throws AuthFailureError {

         return mHeaders;

      }

      @Override

    7. byte[] getBody() {

         ByteArrayOutputStream bos = new ByteArrayOutputStream();
         try {
             // multipart body
             mMultiPartEntity.writeTo(bos);
         } catch (IOException e) {
             Log.e("", "IOException writing to ByteArrayOutputStream");
         }
         return bos.toByteArray();

      }

      @Override

    8. Response<String> parseNetworkResponse(NetworkResponse response) {

         String parsed = "";
         try {
             parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
         } catch (UnsupportedEncodingException e) {
             parsed = new String(response.data);
         }
         return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));

      }

      @Override

    9. void deliverResponse(String response) {

         if (mListener != null) {
             mListener.onResponse(response);
         }

      }

    }

    /**

    • @param account

    • @param bitmap

    • @param webUrl

    • @param uploadListener
      */

    1. static void uploadImage(String account, Bitmap bitmap, String webUrl, final UploadListener uploadListener) {

        UploadFileRequest uploadFileRequest = new UploadFileRequest(webUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
    
                uploadListener.uploadComplete(s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                uploadListener.uploadFail(volleyError);
    
            }
        });
    
        // 获取MultipartEntity对象
        UploadFileEntity multipartEntity = uploadFileRequest.getMultiPartEntity();
        multipartEntity.addStringPart("account", account);
    
        // 文件参数
    
        uploadFileRequest.setTag("uploadImage");
        //加入队列
        ReporterApp.getQueue().add(uploadFileRequest);
    }
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文