0

Cakephp で作成した Web サイトがあります。アプリで形成されたいくつかの値をこの Web サイトに渡したいです。ブラウザにまったく同じ 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 に答える