【问题标题】:Android - How can I upload a txt file to a website?Android - 如何将 txt 文件上传到网站?
【发布时间】:2011-03-02 18:02:30
【问题描述】:

我想上传一个 txt 文件到一个网站,我承认我没有仔细研究过它,但我看过一些例子,希望有更多有经验的意见关于我是否要加入正确的方向。

这是我目前所拥有的:


DefaultHttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
private String ret;

HttpResponse response = null;
HttpPost httpPost = null;


public String postPage(String url, String data, boolean returnAddr) {

    ret = null;

    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);

    httpPost = new HttpPost(url);
    response = null;

    StringEntity tmp = null;         

    try {
        tmp = new StringEntity(data,"UTF-8");
    } catch (UnsupportedEncodingException e) {
        System.out.println("HTTPHelp : UnsupportedEncodingException : "+e);
    }

    httpPost.setEntity(tmp);

    try {
        response = httpClient.execute(httpPost,localContext);
    } catch (ClientProtocolException e) {
        System.out.println("HTTPHelp : ClientProtocolException : "+e);
    } catch (IOException e) {
        System.out.println("HTTPHelp : IOException : "+e);
    } 
            ret = response.getStatusLine().toString();

            return ret;
}

我这样称呼它:


postPage("http://www.testwebsite.com", "data/data/com.testxmlpost.xml/files/logging.txt", true));

我希望能够将文件从设备上传到网站。

但是当我尝试这种方式时,我得到了以下响应。


HTTP/1.1 405 Method Not Allowed

我是在尝试正确的方式还是应该换一种方式?

【问题讨论】:

    标签: java android http upload http-post


    【解决方案1】:

    该代码看起来合理,错误来自服务器,表明该页面不允许 POST。

    您正在发送文字字符串“data/data/com.testxmlpost.xml/files/logging.txt”。如果您想发布文件,请使用FileEntity

    【讨论】:

    • 谢谢我在想,我可以问一下代码是试图发布位于 data/data/com.testxmlpost.xml/files/logging.txt 的文件还是试图发布字符串“数据/数据/com.testxmlpost.xml/files/logging.txt”?
    • 字符串。您可以改用 FileEntity。
    • 谢谢 Matthew,我已将其更改为文件实体,并且我正在使用已设置为允许上传的服务器,但我得到相同的响应,是否有其他方法可以做到而不是使用 POST?
    • @Donal,你使用的实体和方法是分开的。只要你使用HttpPost,它就会是一个POST请求。您需要准确找出服务器希望您使用的方法和格式。
    • 还有一个问题 Matthew,我发现服务器需要 PUT 方法并已更改为该方法。我得到的响应是 403 Forbidden,从阅读这篇文章中我是否正确地说这不是授权错误,而是意味着服务器识别该方法但不喜欢该格式?通过格式这就是我设置 HttpClient 和 HttpPUT 的方式?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 2011-03-27
    • 1970-01-01
    • 2020-02-01
    • 2012-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多