Java 在Android中使用AsyncTask时出现错误代码400,有人能帮我一下吗

Java 在Android中使用AsyncTask时出现错误代码400,有人能帮我一下吗,java,android,api,android-asynctask,Java,Android,Api,Android Asynctask,这是我需要实现的api: 这是我的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.uti

这是我需要实现的api:

这是我的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;
    }
}


包http;
导入android.app.AlarmManager;
导入android.app.pendingent;
导入android.content.Context;
导入android.content.Intent;
导入android.graphics.Bitmap;
导入android.os.AsyncTask;
导入android.util.Log;
导入data.DriverPref;
导入my.daidendriver.R;
导入org.json.JSONException;
导入org.json.JSONObject;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.ByteArrayInputStream;
导入java.io.ByteArrayOutputStream;
导入java.io.DataInputStream;
导入java.io.DataOutputStream;
导入java.io.FileInputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.io.UnsupportedEncodingException;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.net.urlcoder;
导入data.ConfigPref;
导入data.TokenPref;
导入模型.Const;
进口服务.LocationModeratorIntentService;
导入utils.AppInfoUtil;
导入utils.DialogUtil;
导入utils.ImageStorageUtil;
导入视图.home活动;
公共类positionrDuty扩展异步任务{
私人最终字符串标签=“岗位职责”;
私人家庭活动;
私有上下文;
私有布尔值mNetworkFailed=false;
私有布尔onDuty;
私有布尔发现移位;
私有长时间戳;
私有ConfigPref ConfigPref;
私人司机REF司机REF;
私有令牌pref令牌pref;
来自的私有字符串;
私有位图mBitmap;
私有字符串文件名;
私人国际httpResponse;
公共姿势职责(上下文上下文、布尔onDuty、布尔isCoveredShift、位图){
this.mContext=上下文;
this.onDuty=onDuty;
this.configPref=新的configPref(mContext);
this.driverPref=新的driverPref(mContext);
this.tokenPref=新的tokenPref(mContext);
this.isCoveredShift=isCoveredShift;
this.mBitmap=位图;
this.from=“Context”;
}
公共姿势职责(HomeActivity HomeActivity、boolean onDuty、boolean isCoveredShift、位图){
this.homeActivity=homeActivity;
this.mContext=家庭活动;
this.onDuty=onDuty;
this.configPref=新的configPref(mContext);
this.driverPref=新的driverPref(mContext);
this.tokenPref=新的tokenPref(mContext);
this.isCoveredShift=isCoveredShift;
this.mBitmap=位图;
this.from=“HomeActivity”;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
if(from.equals(“家庭活动”)){
DialogUtil.startProgressDialog(mContext,mContext.getResources().getString(R.string.progress\u waiting\u dialog\u content));
}
Log.d(标签“onPreExecute:”);
}
@凌驾
受保护的Void doInBackground(Void…参数){
HttpURLConnection conn=null;
DataOutputStream dos=null;
FileInputStream FileInputStream;
字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“-”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
字符串文件名=ImageStorageUtil.tempFileImage(mContext,mBitmap,“selfie”);
Log.d(标记“doInBackground:filename”+filename);
/**设置HTTP超时**/
试一试{
ByteArrayOutputStream=新建ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.JPEG,100,流);
InputStream is=newbytearrayinputstream(stream.toByteArray());
URL=新URL(configPref.getUrlPrefix()+“用户/职责”);
int timeoutConnection=Integer.parseInt(configPref.getTimeoutConnection(),10)*1000;
int timeoutSocket=10000;
conn=(HttpURLConnection)url.openConnection();
/**超时**/
连接设置连接超时(超时连接);
连接设置读取超时(timeoutSocket);
/**设置HTTP头**/
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“内容类型”、“多部分/表单数据;边界=“+boundary”);
conn.setRequestProperty(“应用程序版本”,AppInfoUtil.getVersion(mContext));
conn.setRequestProperty(“uid”,driverPref.getUid());
conn.setRequestProperty(“访问令牌”,tokenPref.getAccessToken());
conn.setDoInput(真);
连接设置输出(真);
conn.SETUSECHACHES(假);
dos=新的DataOutputStream(conn.getOutputStream());
写字节(两个连字符+边界+行结束);
dos.writeBytes(“内容处置:表单数据;名称=\“pic\”文件名=\“1001.jpg\”+lineEnd);//上载的\u文件\u名称是要上载的文件的名称
dos.writeBytes(“内容类型:图像/jpeg”+lineEnd);
dos.writeBytes(“内容传输编码:二进制”+lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable=is.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
bytesRead=is.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=is.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=is.read(缓冲区,0,缓冲区大小);
}
dos.writeBytes(lineEnd);
写字节(两个连字符+边界+两个连字符+行结束);
is.close();
dos.flush();
D