【问题标题】:Post Image To REST API in android在android中将图像发布到REST API
【发布时间】:2016-05-30 09:28:24
【问题描述】:

我想在 android 中将图像发送到 REST API。我创建了一个 android 应用程序,它只是对 API 进行请求调用并返回响应,但我知道我必须将图像发布到 REST API。

这是我的代码。

    private class PostImage extends AsyncTask<String, String, String> {
      @Override
      protected String doInBackground(String... data) {
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        URL url = new URL("http://localhost:8080/JAXRS-FileUpload/rest/files/upload");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        }
    }

我怎样才能发出将图像发布到 REST API 的发布请求。这是 REST API 代码。

@Path("/files")
public class JerseyFileUpload {
@POST
    @Path("/upload")
    @Consumes(MediaType.)
    @Produces(MediaType.APPLICATION_JSON)
    public ImageUrl responseMsg(){
    //do something
    }

应该使用哪种媒体类型来消费图像。

【问题讨论】:

    标签: android api rest android-asynctask


    【解决方案1】:
    MultipartEntity entity = new MultipartEntity();
    FileBody userPhoto = new FileBody(new File(path));
    entity.addPart("file", userPhoto);
    
    String url = UPDATE_PROFILE_URL;
    HttpParams params1 = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params1, false);
    
    int timeOut = 2 * 60 * 1000;
    
    HttpConnectionParams.setConnectionTimeout(params1, timeOut);
    HttpConnectionParams.setSoTimeout(params1, timeOut);
    DefaultHttpClient httpClient = new DefaultHttpClient(params1);
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entity);
    HttpResponse response = null;
    JSONObject jsResp = null;
            try {
                response = httpClient.execute(httpPost);
                HttpEntity resEntity = response.getEntity();
    
                String sServerResponse = EntityUtils.toString(resEntity);
                Log.i("abc", "FROM: POST:" + sServerResponse);
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
    

    【讨论】:

    • 如何在服务器上接收该图像?意味着我应该在 REST API 中使用哪种 MediaType?
    • 在这种情况下,Web 服务上的媒体类型将为 MediaType.MULTIPART_FORM_DATA
    【解决方案2】:

    我个人使用 loopj 进行客户端-服务器通信,并且可以使用其中的文件发送图像。在您的应用程序 gradle 中添加以下依赖项以使用 loopj

    compile 'com.loopj.android:android-async-http:1.4.9'
    

    然后发送图片

    public void sendAllData() {
        String Url = "your url here";
        //If any auth is needed
        String username = "username";
        String password = "password";
    
        Cursor cursor = mContext.getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
        if (cursor != null && cursor.moveToLast()) {
            Uri fileURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
            fileSrc = fileURI.toString();
            cursor.close();
        }
    
        // Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
        AsyncHttpClient client = new AsyncHttpClient();
        client.setBasicAuth(username, password);
        RequestParams params = new RequestParams();
        try {
            params.put("pic", storeImage());
        } catch (FileNotFoundException e) {
            Log.d("MyApp", "File not found!!!" + fileSrc);
        }
        client.post(Url, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
                //Do what's needed
            }
    
            @Override
            public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
                //Print error
            }
        });
    
    }
    
    private File storeImage() {
        String filename = "anyName";
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
    
        File file = new File(extStorageDirectory, filename + ".jpg");
        try {
            outStream = new FileOutputStream(file);
            bookImage.compress(CompressFormat.JPEG, 80, outStream);
            outStream.flush();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }
    

    【讨论】:

      【解决方案3】:

      您实现了一个服务并在其中发布图像,请查看我的示例here

      检查 postMultiPart 方法。

      【讨论】:

        【解决方案4】:

        将其更改为: 多部分/表单数据

        【讨论】:

        • 我想通过 imageview 显示许多图像。例如,我有一个包含 10 个索引的数组,并且在循环中我想显示 10 个图像我该怎么做。
        • 您在数组中有 URL?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-15
        • 1970-01-01
        • 2012-03-03
        • 2013-05-04
        相关资源
        最近更新 更多