【问题标题】:android http post multipart/form-dataandroid http post 多部分/表单数据
【发布时间】:2022-11-22 12:21:13
【问题描述】:

我需要将字符串和字节数组(图像文件)作为 POST 方法发送到 http 端点。

没学过Android编程,Java也不行,所以想知道自己的代码写的对不对。

当我用 postman 测试时,json 响应很好,但是当我从 android 将它作为 POST 发送时,发生了 400 错误。

(图像在安卓手机的存储中。)

  • 邮递员捕获

  • 请求 HttpURLConnection(REAL POST 类)

public class RequestHttpURLConnection {
    public String request(String _url, String _accessKey, byte[] _values){

        HttpURLConnection urlConn = null;

        try{
            String crlf = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";

            URL url = new URL(_url);
            urlConn = (HttpURLConnection) url.openConnection();

            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            urlConn.setUseCaches(false);
            urlConn.setRequestMethod("POST");
            urlConn.setRequestProperty("Connection", "Keep-Alive");
            urlConn.setRequestProperty("Cache-Control", "no-cache");
            urlConn.setRequestProperty("User-Agent", "CodeJava Agent");
            urlConn.setRequestProperty("Accept-Charset", "UTF-8");
            urlConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            OutputStream os = urlConn.getOutputStream();
            DataOutputStream request = new DataOutputStream(os);

            // 1. Access Key
            request.writeBytes(twoHyphens + boundary + crlf);
            request.writeBytes("Content-Disposition: form-data; name=\"accessKey\""+ crlf);
            request.writeBytes("Content-Type: application/json" + crlf);
            request.writeBytes(crlf);
            request.writeBytes(_accessKey + crlf);

            // 2. Image data
            request.writeBytes(twoHyphens + boundary + crlf);
            request.writeBytes("Content-Disposition: form-data; name=\"files\""+ crlf);
            request.writeBytes("Content-Type: any" + crlf);
            request.writeBytes(crlf);
            request.write(_values);

            request.writeBytes(crlf);
            request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
            request.flush();
            request.close();

            int response_code = urlConn.getResponseCode();

            if (urlConn.getResponseCode() != HttpURLConnection.HTTP_OK){
                System.out.println("Connection Fail! > Responce Code : " + Integer.toString(response_code));
                return "Response Code : " + Integer.toString(response_code);
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));

            String line;
            String page = "";

            while ((line = reader.readLine()) != null){
                page += line;
            }
            System.out.println("Input Stream : " + page);

            return page;

        } catch (IOException e) { // for URL.
            e.printStackTrace();
        } finally {
            if (urlConn != null)
                urlConn.disconnect();
        }
        return null;
    }
}
  • 主要活动
public void onClick(View arg0) {
    System.out.println("[Send to Server] Button is clicked.");

    Bitmap original_bitmap = null;
    Bitmap copied_original_bitmap = null;

    StringBuffer values_buffer = new StringBuffer();
    String url_string = "http://myserver.com/api/inference";
    String accessKey_string = "abcd1234";

    try {
        resultTextView.setText("Inference in progress...");

        // Getting the image from the image view
        //Read the image as Bitmap
        original_bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

        ByteArrayOutputStream blob = new ByteArrayOutputStream();
        original_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, blob);
        byte[] imageBytes = blob.toByteArray();

        System.out.println("create NetworkTask object");
        NetworkTask networkTask = new NetworkTask(url_string, accessKey_string, imageBytes, resultTextView);
        System.out.println("NetworkTask execute.");
        networkTask.execute();
        System.out.println("NetworkTask execution is terminated.");

    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("exception");
        System.out.println("Message:" + e.toString());

    } catch (Exception e) {
        System.out.println("Failed to open image file.");
        finish();
    }
}
  • NetworkTask 类 (+AsyncTask)
public class NetworkTask extends AsyncTask<Void, Void, String> {
    private String url;
    private String accessKey;
    private byte[] values;
    private TextView _resultView;

    public NetworkTask(String url, String accessKey, byte[] values, TextView resultView) {
        this.url = url;
        this.accessKey = accessKey;
        this.values = values;
        this._resultView = resultView;
    }

    @Override
    protected String doInBackground(Void... params) {
        String result;
        RequestHttpURLConnection requestHttpURLConnection = new RequestHttpURLConnection();
        result = requestHttpURLConnection.request(url, accessKey, values); 

        try {
            if (result != null) {
                System.out.println("[doInBackground] output : " + result.toString());
            } else {
                System.out.println("[doInBackground] output is null state.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        System.out.println("[onPostExecute] routine is started.");
        super.onPostExecute(result);

        output = result;
        _resultView.setText(result);

        try{
            if (result != null) {
                System.out.println("[onPostExecute] output : " + result.toString());
            } else {
                System.out.println("[onPostExecute] output is null state.");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我在谷歌上搜索了好几天,但找不到确切的答案。 请看看我的代码。谢谢你。

【问题讨论】:

  • 我为此使用了 Volley,非常非常简单易用!去谷歌上查询
  • @Avital哦谢谢!我会试试看,稍后我会告诉你!

标签: java android http post multipartform-data


【解决方案1】:
猜你喜欢
  • 2017-07-02
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 2014-03-29
  • 1970-01-01
  • 2015-07-07
  • 2021-12-12
  • 1970-01-01
相关资源
最近更新 更多