java - 谁能帮助我解决在 Android 中使用 AsyncTask 时收到错误代码 400 的问题

标签 java android api android-asynctask

这是我需要实现的API:
api to implement
这是我的 api 代码实现

package http;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.util.Log;

import data.DriverPref;
import my.daidendriver.R;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import data.ConfigPref;
import data.TokenPref;
import models.Const;
import services.LocationModeratorIntentService;
import utils.AppInfoUtil;
import utils.DialogUtil;
import utils.ImageStorageUtil;
import views.HomeActivity;

public class PostUserDuty extends AsyncTask<Void, Void, Void> {

    private final String TAG = "post-duty";
    private HomeActivity homeActivity;
    private Context mContext;
    private boolean mNetworkFailed = false;

    private boolean onDuty;
    private boolean isCoveredShift;
    private long currentTimestamp;

    private ConfigPref configPref;
    private DriverPref driverPref;
    private TokenPref tokenPref;
    private String from;
    private Bitmap mBitmap;
    private String fileName;
    private int httpResponse;

    public PostUserDuty(Context context, boolean onDuty, boolean isCoveredShift, Bitmap bitmap) {
        this.mContext = context;
        this.onDuty = onDuty;
        this.configPref = new ConfigPref(mContext);
        this.driverPref = new DriverPref(mContext);
        this.tokenPref = new TokenPref(mContext);
        this.isCoveredShift = isCoveredShift;
        this.mBitmap = bitmap;
        this.from = "Context";
    }

    public PostUserDuty(HomeActivity homeActivity, boolean onDuty, boolean isCoveredShift, Bitmap bitmap) {
        this.homeActivity = homeActivity;
        this.mContext = homeActivity;
        this.onDuty = onDuty;
        this.configPref = new ConfigPref(mContext);
        this.driverPref = new DriverPref(mContext);
        this.tokenPref = new TokenPref(mContext);
        this.isCoveredShift = isCoveredShift;
        this.mBitmap = bitmap;
        this.from = "HomeActivity";
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        if (from.equals("HomeActivity")) {
            DialogUtil.startProgressDialog(mContext, mContext.getResources().getString(R.string.progress_waiting_dialog_content));
        }
        Log.d(TAG, "onPreExecute: ");
    }

    @Override
    protected Void doInBackground(Void... params) {
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        FileInputStream fileInputStream;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "-";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String filename = ImageStorageUtil.tempFileImage(mContext, mBitmap, "selfie");
        Log.d(TAG, "doInBackground: filename " + filename);

        /**Set HTTP Timeout**/
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            InputStream is = new ByteArrayInputStream(stream.toByteArray());
            URL url = new URL(configPref.getUrlPrefix() + "user/duty");
            int timeoutConnection = Integer.parseInt(configPref.getTimeoutConnection(), 10) * 1000;
            int timeoutSocket = 10000;
            conn = (HttpURLConnection) url.openConnection();
            /**  timeout **/
            conn.setConnectTimeout(timeoutConnection);
            conn.setReadTimeout(timeoutSocket);

            /**Set HTTP Header**/
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            conn.setRequestProperty("app-version", AppInfoUtil.getVersion(mContext));
            conn.setRequestProperty("uid", driverPref.getUid());
            conn.setRequestProperty("access-token", tokenPref.getAccessToken());
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);

            dos.writeBytes("Content-Disposition: form-data; name=\"pic\";filename=\"1001.jpg\"" + lineEnd); // uploaded_file_name is the Name of the File to be uploaded
            dos.writeBytes("Content-Type: image/jpeg" + lineEnd);
            dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
            dos.writeBytes(lineEnd);
            bytesAvailable = is.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            bytesRead = is.read(buffer, 0, bufferSize);
            while (bytesRead > 0) {
                dos.write(buffer, 0, bufferSize);
                bytesAvailable = is.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = is.read(buffer, 0, bufferSize);
            }
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            is.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.d(TAG, "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.d(TAG, "error: " + ioe.getMessage(), ioe);
        }

        /**Set HTTP body**/
        JSONObject jsonParam = new JSONObject();
        try {
            jsonParam.put("uploadedFiles", filename);
            JSONObject dataobject = new JSONObject();
            if (onDuty) {
                dataobject.put("dutyState", 1);
            } else {
                dataobject.put("dutyState", 0);
            }
            if (isCoveredShift) {
                dataobject.put("isCoveredShift", 1);
            } else {
                dataobject.put("isCoveredShift", 0);
            }
            currentTimestamp = System.currentTimeMillis() / 1000;
            dataobject.put("timestamp", currentTimestamp);
            dataobject.put("reason", "Emergency");
            jsonParam.put("data", dataobject);

            Log.d(TAG, "dutyState: " + onDuty);
            Log.d(TAG, "timestamp: " + currentTimestamp);
            Log.d(TAG, "doInBackground: payload: " + jsonParam);
        } catch (JSONException ex) {
            ex.printStackTrace();
        }


        try {
            httpResponse = conn.getResponseCode();
            Log.d(TAG, "Response code:" + httpResponse);

            /**Get input**/
            InputStream inputStream;
            if (httpResponse >= HttpURLConnection.HTTP_BAD_REQUEST)
                inputStream = conn.getErrorStream();
            else
                inputStream = conn.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();

            String line = null;
            String result = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            Log.d(TAG, sb.toString());
            result = sb.toString().trim();
            JSONObject jObject = null;
            jObject = new JSONObject(result);
            if (jObject.getString("code").equals("0")) {
                Log.d(TAG, "Duty Status Selfie Saved successfully.");
                fileName = jObject.getString("selfieFileName");
            } else { //else if network error
                mNetworkFailed = true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }
}




当我尝试使用调试器时,我的每一行代码都完美执行,但我收到错误代码 400 作为响应代码,我没有明白出了什么问题,任何人都可以帮助我找出我的错误。这是我的第一个 stackoverflow 问题,如果格式错误,我深表歉意。

最佳答案

400 错误请求响应状态代码表示服务器由于被认为是客户端错误(例如格式错误的请求语法、无效的请求消息帧或欺骗性请求路由)而无法或不会处理请求。附加错误消息说明了 400 错误的原因。请参阅https://airbrake.io/blog/http-errors/400-bad-request如果您的请求很复杂,请简化或使用简单的请求进行测试,如果可以,请逐步添加到您的请求中。希望这对您有所帮助。

关于java - 谁能帮助我解决在 Android 中使用 AsyncTask 时收到错误代码 400 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60359291/

相关文章:

Android 加速度计设置 : can I get it to run only when button it pressed.

android - Dagger 2 无法识别 Kotlin 中的提供方法。 Java 工作正常

java - 无法访问 com.sun.net.ssl.internal.ssl.Provider() Java Mail Api

java - 是否可以使用 Office 2010 从 Java 应用程序以编程方式打开、编辑和保存 rtf 文件?

java - 当我第一次启动应用程序时,用户名是空的

java - 在 Docker 中运行 Selenium 测试时出现连接被拒绝的 UnreachableBrowserException

java - MP4Parser 创建损坏的 mp4

php - Magento API v2 PHP 错误

python - 不使用 Ibpy 的 IB API Python 示例

java - "deck shuffling"程序 : getting unexpected zeroes in results Java 出现问题