首页 > 解决方案 > 来自 cURL 请求的 AsyncTask 中的 HTTP 请求

问题描述

我已经构建了一个 Web 服务,它将接收图像作为输入,并以 JSON 结果进行响应。

卷曲请求:

curl -X POST -F "file=@images/Sample1.jpg" http://192.168.0.101:5000/Img_Emotion/ 

输出 :

{
    "angry": 0,
    "disgusted": 0,
    "fearful": 0,
    "happy": 99.97,
    "sad": 0,
    "surprised": 0,
    "neutral": 0.03
}

现在我正在尝试构建一个 android 应用程序,该应用程序将使用 HTTP 请求从这个 API 获取响应AsyncTask

到目前为止,我已经为GET方法做了类似的事情而没有发布任何数据。

   @Override
    protected Void doInBackground(String... params) {

        try {
            // This is getting the url from the string we passed in
            URL url = new URL(params[0]);

            // Create the urlConnection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoInput(true);
            urlConnection.setRequestMethod("GET");
            int statusCode = urlConnection.getResponseCode();
            if (statusCode ==  200) {
                InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
                String response = convertInputStreamToString(inputStream);
                Log.e("result",response);
            } 

        } catch (Exception e) {
            Log.d("error", e.getLocalizedMessage());
        }
        return null;
    }
    private String convertInputStreamToString(InputStream inputStream) {
        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            while((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    } 

我需要通过从相机或本地存储向 API 发布图像并取回响应来做到这一点。

标签: androidcurlandroid-asynctaskhttprequest

解决方案


推荐阅读