2012-11-07 82 views
0

我有一个使用cakephp创建的网站。我想将我的应用程序中形成的一些值传递给此网站。当我在浏览器中输入完全相同的URL时,它可以工作。CakePHP的Android HTTP请求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) { 
} 

回答

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() recive。它可能会帮助你。

+0

我很抱歉,我认为8不够清楚。我的网址不包含PHP文件或任何东西。只是一个普通的URL(CakePHP创建它们的方式...)服务器直接从URL读取值。还有其他的方式吗? – user754730

+0

你有一个类似'www.something.com/function/add /'的链接,带有一些值。尝试在服务器上查找处理程序文件。在这个目录中'function/add /'必须是'index.php'。在那儿? – validcat

+0

不,没有PHP文件,也没有办法可以做到。链接www.something.com/function/add/myvaluetobeadded就是这样的。然后CakePHP知道“myvaluetobeadded”是我给网站的实际价值,如果我用浏览器导航到网站,它的效果很好。 – user754730