如何从android连接获取responsebody消息

时间:2017-08-23 05:50:16

标签: javascript android forms http httpurlconnection

我使用webview上传android图像文件。

这是我的服务器端(带弹簧)

@RequestMapping(value = "/mobile/android.do", method = RequestMethod.POST)
public @ResponseBody String android(

        final MultipartHttpServletRequest multiRequest
    ) throws Exception {

    LOGGER.info("/mobile/androidFileUpload.do {}","sfsdfsd");
    Map<String, Object> map = new HashMap<>();
    return "sdfdsfsdfds";

}

我想从android获取此responsebody消息并将其返回。

这是我的机器人方面。实际上服务器连接正常。

@JavascriptInterface
    public int uploadFile(final String selectedFilePath){

.......

    URL url = new URL(SERVER_URL_FILE+"/mobile/android.do");
                Log.i(fileName,"File url = "+ url);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);//Allow Inputs
                connection.setDoOutput(true);//Allow Outputs
                connection.setUseCaches(false);//Don't use a cached Copy
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Connection", "Keep-Alive");
                connection.setRequestProperty("ENCTYPE", "multipart/form-data");
                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                connection.setRequestProperty("uploaded_file",selectedFilePath);
//creating new dataoutputstream
                dataOutputStream = new DataOutputStream(connection.getOutputStream());



                //writing bytes to data outputstream
                dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
                dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + selectedFilePath + "\"" + lineEnd);

                dataOutputStream.writeBytes(lineEnd);

                //returns no. of bytes present in fileInputStream
                bytesAvailable = fileInputStream.available();
                //selecting the buffer size as minimum of available bytes or 1 MB
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                //setting the buffer as byte array of size of bufferSize
                buffer = new byte[bufferSize];

                //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
                bytesRead = fileInputStream.read(buffer,0,bufferSize);

                if(fileInputStream==null)     Log.v(path,"File input null");
                else       Log.v(path,"File input not null");
                //loop repeats till bytesRead = -1, i.e., no bytes are left to read

                while (bytesRead > 0){
                    //write the bytes read from inputstream
                    Log.v(path,"read");
                    dataOutputStream.write(buffer,0,bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable,maxBufferSize);
                    bytesRead = fileInputStream.read(buffer,0,bufferSize);
                }

                dataOutputStream.writeBytes(lineEnd);
                dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();


                Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode + ":" + connection.getRespon);
........
}

日志消息如下。

08-23 14:32:44.681 2040-2607 / com.example.ganedu.permission5 I / PermissionDemo:服务器响应是:OK:200

我想如何获得响应体的值?

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码获得完整的回复正文;

   HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println("statusCode +statusCode");
            if (statusCode == 200) {
                // Server response
                System.out.println("statusCode +statusCode");
                responseString = EntityUtils.toString(r_entity);

                String success= String.valueOf(responseString.contains("1"));

                if (success.equalsIgnoreCase("true"))
                {
                    runOnUiThread(new Runnable(){
                        public void run() {
                    Toast.makeText(getApplicationContext(),"Image Uploaded Successfully",Toast.LENGTH_SHORT).show();
                        }
                    });

                }


            } else {
                responseString = "Error occurred! Http Status Code: " + statusCode;
            }