Android:在一个Http Post Request中发送post params,file和text

时间:2013-09-11 13:49:18

标签: android http post

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

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

所以我的第一个问题是,请求将如何显示?

1)因为我知道帖子参数通常位于正文

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

  

的multipart / form-data的;边界= ---- WebKitFormBoundaryE19zNvXGzXaLvS5C

所以finnaly我的事情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

这是正确的吗?

我的 SECOND 问题是如何在Android上实现它?

我看到每个人都使用MultipartEntity,但它需要额外的开源库,但我的客户端不想使用开源库...所以我必须自己实现。

所以我相信我必须将这个身体放在一个大字符串中,这是正常的还是有更好的解决方案?

1 个答案:

答案 0 :(得分:0)

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

在我的ServerController.class中:

AsyncTask to POST / GET calls

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 {
    }
}