如何制作在Android Studio中使用凌空上传图像的分段方法

问题描述 投票:0回答:1

我有一个ApiHelper类,用于在我的项目中请求API。我想为分段上传图像提供一种方法。我不知道如何在android中进行multipart的方法。 Volley用于多部分方法。有两种方法类似于需要多部分方法。我正在这里发布我的ApiHelper类。

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import static com.android.volley.Request.Method.POST;

/**
 * Created by Gourav on 09-02-2017.
 */

public class ApiHelper {
    private static ApiHelper mInstance;
    private RequestQueue mRequestQueue;
    Context context;

    ApiHelper(Context context) {
        this.context = context;
    }

    public static synchronized ApiHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new ApiHelper(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public void doGetRequest(String url, final HashMap<String, String> headers, final ApiCallback callback) {
        Log.d("url", "" + url);
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse", "" + response);
                        try {
                            callback.onResponse(response);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.d("onErrorResponse", "" + error.getMessage());
                        callback.onError("Server error");
                    }
                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers != null) {
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }

        };
        addToRequestQueue(jsObjRequest);
    }

    public void doPostRequest(String url, final HashMap<String, String> headers, final JSONObject jsonObject, final ApiCallback callback) {
        Log.d("url", "" + url);
        Log.d("url", "" + jsonObject.toString());
        url = url.replace(" ", "%20");
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (POST, url, jsonObject, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("onResponse", "" + response);
                        if (response != null) {
                            try {
                                callback.onResponse(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            callback.onError("Null");
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        Log.d("onErrorResponse", "" + error.getMessage());
                        if (error instanceof TimeoutError) {
                            callback.onError("Timeout bad network");
                        } else
                            callback.onError(error.getMessage());
                    }

                }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                if (headers != null) {
                    return headers;
                } else {
                    return super.getHeaders();
                }
            }
        };
        try {
            Log.d("headers", "" + jsObjRequest.getHeaders().toString());
        } catch (AuthFailureError authFailureError) {
            authFailureError.printStackTrace();
        }
        addToRequestQueue(jsObjRequest);
    }

}
android api android-volley multipart uploading
1个回答
0
投票

创建名为MultipartUtilityPOST.java的新类

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class MultipartUtilityPOST {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;

/**
 * This constructor initializes a new HTTP POST request with content type
 * is set to multipart/form-data
 * @throws IOException
 */
public MultipartUtilityPOST(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestMethod("POST");
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

/**
 * Adds a form field to the request
 *
 * @param name  field name
 * @param value field value
 */
public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a upload file section to the request
 *
 * @param fieldName  name attribute in <input type="file" name="..." />
 * @param uploadFile a File to be uploaded
 * @throws IOException
 */
public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();
}

/**
 * Adds a header field to the request.
 *
 * @param name  - name of the header field
 * @param value - value of the header field
 */
public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}

/**
 * Completes the request and receives response from the server.
 *
 * @return a list of Strings as response in case the server returned
 * status OK, otherwise an exception is thrown.
 * @throws IOException
 */
public String finish() throws IOException {
    StringBuffer response ;

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        response = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response.toString();
}
}

从您想要触发API请求的位置调用addFilePart方法

    String charset = "UTF-8";

    MultipartUtilityPOST multipart;
    try {
    multipart = new MultipartUtilityPOST("API URL", charset);
    multipart.addFilePart("content", new File(your_file_path));
    multipart.addFormField("content_type", "image/jpeg");
    String response = multipart.finish();
    catch (Exception e)
    {
       e.printStackTrace();
    }
© www.soinside.com 2019 - 2024. All rights reserved.