HttpPost无法正常工作!

时间:2010-11-25 01:03:30

标签: android http http-post

我正在尝试将内容写入我的apache服务器上的空文件

myClient= new DefaultHttpClient();

StringEntity myString = new StringEntity("important message");
HttpPost httpPost = new HttpPost("http://10.0.218.211/myfile");
httpPost.setEntity(myString);

HttpResponse response = myClient.execute(httpPost);

响应返回“HTTP / 1.1 200 OK”,因此它确实找到了文件

我尝试删除该文件并返回错误404

我读了apache的文档,看起来正在做“我认为”

我的问题是...文件内容没有更新!

一个例子很棒!

2 个答案:

答案 0 :(得分:4)

试试这个:

url = "http://10.0.218.211/post.php"; 

HttpClient httpclient = new DefaultHttpClient();  
HttpPost post = new HttpPost(url);  

try {  
        **// Add your data <-**
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
        nameValuePairs.add(new BasicNameValuePair("message", "important message 1"));  
        nameValuePairs.add(new BasicNameValuePair("message2", "important message 2"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));  

        // Execute HTTP Post Request  
        HttpResponse response = httpclient.execute(post);  

        } catch (ClientProtocolException e) {  
        / TODO Auto-generated catch block  
        } catch (IOException e) {  
        // TODO Auto-generated catch block  
        }
  }

<强>的AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

<强> post.php中

<?php

$message = $_POST['message'];

// Load XML file
$xml = simplexml_load_file("myfile.xml"); 

 //In this line it create a SimpleXMLElement object with the source of the XML file.
$sxe = new SimpleXMLElement($xml->asXML());

//The following lines will add a new child and others child inside the previous child created.
$item = $sxe->addChild("item");
$item->addChild("message", $message);

//This next line will overwrite the original XML file with new data added
$sxe->asXML("myfile.xml"); 

?>

<强> myfile.xml中

<?xml version="1.0" encoding="utf-8" ?>
<data>
    <item>
        <message>Important Message</messagee>
    </item>
</data>

答案 1 :(得分:0)

你可能想调用setcontentType。 例如

StringEntity myString = new StringEntity("important message");
myString.setContentType("application/json");//or what ever your server expected
HttpPost httpPost = new HttpPost("http://10.0.218.211/myfile");
httpPost.setEntity(myString);