0

我有一个用 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) {
}
4

1 回答 1

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

$response在您的 java 代码中作为HttpEntity entity = response.getEntity(). 它可能会帮助你。

于 2012-11-07T11:22:22.597 回答