1

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

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

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

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

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,但它需要额外的开源库,但我的客户不想使用开源库......所以我必须自己实现。

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

4

1 回答 1

0

看看我在我的应用程序中使用的内容:

在我的 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-11T14:13:30.850 回答