问题
I have a website which was created with cakephp. I want to pass some values formed in my App to this website. When I enter the exact same URL in the browser it works.
The URL is something like: www.something.com/function/add/value
So I'm very confused if this is a GET or a POST method? And how I can do that?
The thing is that I can NOT change this URL or put some POST or GET PHP script there to get the values. So I basically just have to call the URL with those params.
This is my code:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = null;
try {
httppost = new HttpPost("www.something.com/function/add/" + URLEncoder.encode(txtMessage.getText().toString(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
httpclient.execute(httppost, responseHandler);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
回答1:
Create List<NameValuePair>
and put here yours values ("somevalue" in example). Create DefaultHttpClient()
set nameValuePairs
with yours value.
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("tag", "TEST_TAG"));
nameValuePairs.add(new BasicNameValuePair("valueKey", "somevalue"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("www.something.com/function/add/utils.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
Log.i("response", sb.toString());
On the server side in /function/add/utils.php
get yours value
if (isset($_POST['tag']) && $_POST['tag'] != '') {
$tag = $_POST['tag']; //=TEST_TAG
$value = $_POST['valueKey']; //=somevalue
}
//and return some info
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$response["success"] = 1;
echo json_encode($response);
This $response
you recive in your java code as HttpEntity entity = response.getEntity()
. It may help you.
来源:https://stackoverflow.com/questions/13267806/android-http-request-for-cakephp-url