尝试上传图片时,android中不支持的媒体类型错误

时间:2013-07-30 12:24:27

标签: java android

我正在尝试创建一个将图像上传到服务器的应用程序。我从服务器收到响应415 unsupported media type。我的代码如下,我应该做些什么改变?

class RetreiveFeedTask extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... url){
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
            Bitmap bitmap = drawable.getBitmap();
            bitmap.compress(CompressFormat.JPEG, 50, bos);
            byte[] data = bos.toByteArray();

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://10.155.103.167:9090/RestServer/rest/todos");

            String fileName = String.format("File_%d.png", new Date().getTime());
            ByteArrayBody bab = new ByteArrayBody(data, fileName);

            ContentBody mimePart = bab;

            // File file= new File("/mnt/sdcard/forest.png");
            // FileBody bin = new FileBody(file);

            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("file", bab);
            postRequest.setEntity(reqEntity);
            int timeoutConnection = 60000;
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 60000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            HttpConnectionParams.setTcpNoDelay(httpParameters, true);
            HttpResponse response = httpClient.execute(postRequest);

            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            String sResponse;
            StringBuilder s = new StringBuilder();
            System.out.println("Response: " + response.getStatusLine());
            while ((sResponse = reader.readLine()) != null) {
                s = s.append(sResponse);
            }
            //txt.setText("NEW TEXT"+s);
        } catch (Exception e) {
            // handle exception here
            e.printStackTrace();
            System.out.println(e.toString());
        }
        return null;
    }
}

1 个答案:

答案 0 :(得分:1)

我也遇到了同样的问题,设置内容类型应解决问题

headers.put("Content-Type", "application/json");