繁体   English   中英

Android:在一个Http Post Request中发送发布参数,文件和文本

[英]Android: send post params, file, and text in one Http Post Request

我对POST请求的外观以及服务器如何解析它们没有很深的了解,而google没有给出太多答案,这就是为什么我在这里发布此问题。

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

所以我的第一个问题是,请求的外观如何?

1)据我所知post参数通常位于主体中

2)我的内容类型我应该是

多部分/表单数据; boundary = ---- 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,但是它需要附加的开源库,但是我的客户不想使用开源库...所以我必须自己实现。

因此,我认为我必须将这一主体放在一个大的字符串中,这是正常的还是有更好的解决方案?

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

在我的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 {
    }
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM