I am trying to write something to an empty file on my apache server
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);
The reponse returns "HTTP/1.1 200 OK" so it does find the file
I tried removing the file and it returned Error 404
I read apache's docs and looks like am doing it right "i think"
My problem is... the contents of the file do not get updated!
An example would be great!
Try this:
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>
you may want to call setcontentType. For example
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);
来源:https://stackoverflow.com/questions/4272905/httppost-not-working