从java连接到php api

时间:2014-06-15 00:01:18

标签: java php json api post

我正在尝试连接到从Java客户端用PHP编写的api。

为了简化问题,我将api减少到以下内容:(它只返回给服务器的请求)

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
$applications = array(
   'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key  for php client
   'APP002' => '38e336ac6c9423d946ba02d19c6a2632' // for java app
);
require_once 'models/TodoItem.php';
echo"request";
foreach ($_REQUEST as $result) {
 echo $result;
 echo "<br>";
} 
echo"end";
exit();

我发送请求如下:(字符串参数是此后代码片段中的字符串)

URL url;
HttpURLConnection connection = null;  
try {
url = new URL(APP_URI);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", 
     "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + 
         Integer.toString(param.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");  
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
   connection.getOutputStream ());
wr.writeBytes (param);
wr.flush ();
wr.close ();
//Get Response  
InputStream is = connection.getInputStream();
// read from input stream

传递的请求字符串如下:(一个带有2个参数的json对象,其中一个是另一个json对象)

{"app_id":"APP002","enc_request":"{\"username\":\"nikko\",\"action\":\"checkUser\",\"userpass\":\"test1234\",\"controller\":\"todo\"}"}

回复如下,其中仅包含我手动回复的开始和结束标记,没有内容:

 requestend

为什么我没有在服务器端获得任何内容?

1 个答案:

答案 0 :(得分:0)

我最终使用了apache的httpclient api。通过结合以下问题的答案:Sending HTTP POST Request In JavaWhat's the recommended way to get the HTTP response as a String when using Apache's HTTP Client?我采取以下解决方案。

注意:我作为json的一部分发送的app_id和enc_request现在作为namedpair的一部分,它遵守服务器端预期的数组。因此,param字符串现在只是:

 {"username":"nikko","action":"checkUser","userpass":"test1234","controller":"todo"}

代码如下:

public static String excutePost(String[][] urlParameters) {
        try {
            String param = encode(urlParameters);
            HttpClient httpclient = HttpClients.createDefault();
            HttpPost httppost = new HttpPost(APP_URI);
            List<NameValuePair> params = new ArrayList<NameValuePair>(2);
            params.add(new BasicNameValuePair("app_id", APP_NAME));
            params.add(new BasicNameValuePair("enc_request", param));
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                String res = EntityUtils.toString(entity);
                return res;
            }
        } catch (IOException e) {
            return null;
        }

        return null;
    }