【问题标题】:Android: send post params, file, and text in one Http Post RequestAndroid:在一个 Http Post 请求中发送 post 参数、文件和文本
【发布时间】:2013-09-11 22:21:23
【问题描述】:

我对 POST 请求的外观以及服务器如何解析它们没有深入的了解,而且谷歌没有给出太多答案,这就是我在这里发布这个问题的原因。

我有 Android 应用程序,用户可以向服务器发送 Http Post 请求, 他能够添加发布参数,在正文中添加一些文本,并附加文件(这是用户想要将所有内容都放在一个请求中的正常情况,对吧?)

所以我的FIRST问题是,请求会是什么样子?

1) 据我所知,post 参数通常位于正文中

2) 我的内容类型应该是

多部分/表单数据;边界=----WebKitFormBoundaryE19zNvXGzXaLvS5C

所以最后我觉得 http 请求会像这样:

POST /upload HTTP/1.1 Host: 192.168.0.1:3333 Cache-Control: no-cache

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="PostParameters"

key=value&key=value

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="Message"

Some text could be here

----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="data"

File data, file data, file data

对吗???

我的第二个问题是如何在android上实现它?

我看到大家都用了MultipartEntity,但是它需要额外的开源库,但是我的客户不想使用开源库……所以我必须自己实现。

所以我相信我必须把这个身体放在一个大绳子里,这是正常的还是有更好的解决方案?

【问题讨论】:

    标签: android http post


    【解决方案1】:

    看看我在我的应用中使用了什么:

    在我的 ServerController.class 中:

    AsyncTask 到 POST/GET 调用

    private final int GET = 0;
    private final int POST = 1;
    
    private class ServerRequestTask extends AsyncTask<Void, Void, Void> {
    
        private URL requestUrl;
        private int request_type;
        private Map<String, String> parameters;
        private JSONObject json_parameters;
        private boolean showDialog;
    
        public ServerRequestTask(URL requestUrl, int request_type, Map<String, String> parameters, boolean showDialog) {
            this.requestUrl = requestUrl;
            this.request_type = request_type;
            this.parameters = parameters;
            this.showDialog = showDialog;
        }
    
        public ServerRequestTask(URL requestUrl, int request_type, JSONObject json_parameters, boolean showDialog) {
            this.requestUrl = requestUrl;
            this.request_type = request_type;
            this.json_parameters = json_parameters;
            this.showDialog = showDialog;
        }
    
        public String doGetRequest(URL requestUrl) {
            String responseString = null;
    
            DefaultHttpClient httpclient = new DefaultHttpClient();
    
            HttpGet httpGet = null;
    
            if(connectedToInternet()) {
                try {
    
                    if(parameters != null) {
                        List<NameValuePair> nameValuePairs = convertParameters(parameters);
                        requestUrl = new URL(requestUrl.toString() + "?" + URLEncodedUtils.format(nameValuePairs, "UTF-8"));
                    }
    
                    httpGet = new HttpGet(requestUrl.toURI());
    
                    HttpResponse response = null;
    
                    response = httpclient.execute(httpGet);
                    responseString = EntityUtils.toString(response
                            .getEntity(), "UTF-8");
                    responseCode = response.getStatusLine().getStatusCode();
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return responseString;
        }
    
        public String doPostRequest(URL requestUrl) {
            String responseString = null;
    
            DefaultHttpClient httpclient = new DefaultHttpClient();
    
            HttpPost httpPost = null;
    
            if(connectedToInternet()) {
                try {
                    httpPost = new HttpPost(requestUrl.toString());
                    if(json_parameters != null) {
                        httpPost.setHeader("Content-type", "application/json");
                    }
    
                    if(parameters != null && json_parameters == null) {
                        List<NameValuePair> nameValuePairs = convertParameters(parameters);
                        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
                    } else if (json_parameters != null) {
                        StringEntity se = new StringEntity(json_parameters.toString(), "utf-8");
                        httpPost.setEntity(se);
                    }
    
                    HttpResponse response = null;
    
                    response = httpclient.execute(httpPost);
                    responseString = EntityUtils.toString(response
                            .getEntity(), "UTF-8");
                    responseCode = response.getStatusLine().getStatusCode();
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return responseString;
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(showDialog) progressDialog.show();
        }
    
        @Override
        protected Void doInBackground(Void... params) {
            switch (request_type) {
            case GET:
                requestResult = doGetRequest(requestUrl);
                break;
            case POST:
                requestResult = doPostRequest(requestUrl);
                break;
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if(showDialog) progressDialog.dismiss(); 
    
            if (onResultReadyListener != null) {
                onResultReadyListener.onResultReady();
            }
        }
    }
    
    private OnRequestResultReadyListener onResultReadyListener;
    

    回调接口

    public interface OnRequestResultReadyListener {
    public void onResultReady();
    }
    

    请求示例:

    public void getItemsList() {
        if(connectedToInternet()) {
            try {
                URL requestUrl = new URL(
                        Constants.ITEMS_LIST_API_URL 
                        ); 
    
                Map<String, String> parameters = new HashMap<String, String>();
                parameters.put("auth_token", "1234567ABC");
    
                itemsListApiTask = new ServerRequestTask(requestUrl, GET, parameters, true);
                itemsListApiTask.execute();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        } else {
            //Handle errors here
        }
    }
    

    这个想法是你可以将任何你想要的东西放入 HashMap、文件或文本中。你也可以用 JSON 代替 HashMap:

    public void postComment(String comment, int rating) {
        if(connectedToInternet()) {
            try {
                URL requestUrl = new URL(
                        Constants.ADD_COMMENT_API_URL); 
    
                JSONObject jsonComments = new JSONObject();
                jsonComments.put("comment", comment);
                jsonComments.put("rating", rating + "");
    
                postCommentApiTask = new ServerRequestTask(requestUrl, POST, jsonComments, false);
                postCommentApiTask.execute();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 2016-06-02
      • 2019-01-13
      • 2013-01-11
      • 1970-01-01
      • 2020-03-22
      • 2013-10-12
      • 1970-01-01
      相关资源
      最近更新 更多