任何人都可以帮助我,在Android中使用AsyncTask时出现错误代码400

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

这是我需要实现的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问题,如果格式错误,我将非常抱歉。

java android api android-asynctask
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.