将原始数据发布到Android

时间:2019-08-26 03:47:24

标签: android http-post postman raw-data

我想使用Asynctask在android中发送发布请求,但没有成功。 在邮递员中,我将原始数据发送到下面,然后得到结果。

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="image"; filename="file name"
Content-Type: image/jpeg
Content-Encoding: base64

------------
/9j/wAARCAQ4B4ADASEAAhEBAxEB/90ABAB4/9sAhAADAgIDAgIDAwMDBAMDBAYJBgYEBAY
MCAgHCQ4MDg4NDA0NEBEWExARFBENDRMbExQXGBkZGQ4SHB0bGB0WGBkYAQMEBAYEBgsGBg
sYEA0QGBgYG....
------WebKitFormBoundary7MA4YWxkTrZu0gW--

我在android中的代码:

public class HttpAsyncTask extends AsyncTask<String, String, String> {

    public HttpAsyncTask(){
        //set context variables if required
    }

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

    @Override
    protected String doInBackground(String... params) {
        String urlString = params[0]; // URL to call
        String data = params[1]; //data to post
        OutputStream out = null;
        String response = "";

        try {
            URL url = new URL(urlString);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("image", data);
            urlConnection.setDoOutput(true);

            out = new BufferedOutputStream(urlConnection.getOutputStream());

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(data);
            writer.flush();
            writer.close();
            out.close();
            int responseCode=urlConnection.getResponseCode();
            Log.i("responseCode ", Integer.toString(responseCode));
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br =new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

            }

//            urlConnection.connect();
        } catch (Exception e) {
            Log.i("HTTP async task", e.toString());
        }

        Log.i("HTTP async task", response);

        return response;
    }

    @Override
    protected void onPostExecute(String response) {
        Log.i("HTTP async task", response);
        super.onPostExecute(response);
    }
}

然后我打电话 new HttpAsyncTask().execute(myurl, based64String);

0 个答案:

没有答案