我有一个用cakephp创建的网站。我想将我的应用程序中形成的一些值传递给本网站。当我在浏览器中输入完全相同的URL时,它可以工作。
URL类似于:www.something.com/function/add/value
如果这是一个GET或POST方法,我很困惑?我怎么能这样做?
问题是我无法更改此URL或在其中放置一些POST或GET PHP脚本来获取值。所以我基本上只需要用这些参数调用URL。
这是我的代码:
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) {
}
答案 0 :(得分:1)
创建List<NameValuePair>
并在此处放置您的值(示例中为“somevalue”)。使用您的值创建DefaultHttpClient()
设置nameValuePairs
。
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());
在/function/add/utils.php
的服务器端获取您的值
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);
您在java代码中将此$response
称为HttpEntity entity = response.getEntity()
。它可能对你有帮助。