【问题标题】:connecting to a php api from java从 java 连接到 php api
【发布时间】:2014-06-15 00:01:17
【问题描述】:

我正在尝试从 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();

我发送请求如下:(string param是后面代码sn-p中的字符串)

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

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

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

回复如下,只包含我手动回显的开始和结束标签,没有内容:

 requestend

为什么我在服务器端收不到任何内容?

【问题讨论】:

  • 你是不是忘了问你的问题,还是我错过了什么?
  • 接收到的对象的 php 中的 json_decode 在哪里?
  • @PeeHaa 是的,你错过了,他问为什么“没有内容”
  • Yes PeeHaa 问题是我没有得到任何内容。我会编辑以使其更清晰。而@Ohgodwhy json_decode 需要一个字符串,所以我需要访问数组中的一个条目才能传递给它,但根本没有条目。

标签: java php json api post


【解决方案1】:

我最终使用了 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 现在是命名对的一部分,它遵循服务器端预期的数组。因此,参数字符串现在只有:

 {"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;
    }

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多