Donal Rafferty
Donal Rafferty

Reputation: 19826

Android - How can I upload a txt file to a website?

I want to upload a txt file to a website, I'll admit I haven't looked into it in any great detail but I have looked at a few examples and would like more experienced opinions on whether I'm going in the right direction.

Here is what I have so far:


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

And I call it as follows:


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

I want to be able to upload a file from the device to a website.

But when trying this way I get the following response back.


HTTP/1.1 405 Method Not Allowed

Am I trying the correct way or should I be doing it another way?

Upvotes: 3

Views: 1744

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

That code looks reasonable, the error is from the server and indicates that POST is not allowed for that page.

You're sending the literal string "data/data/com.testxmlpost.xml/files/logging.txt". If you want to post a file, use a FileEntity.

Upvotes: 3

Related Questions