Java 客戶端調用 PHP 接口,接口返回 JSON 數組,客戶端解析展示。示例環境:PHP 運行在 https://127.0.0.6/?c=json。
<?php
if (isset($_REQUEST['c']) && $_REQUEST['c'] === 'json') {
$arr = [
['id' => 1, 'name' => 'zhdc'],
['id' => 2, 'name' => '小朱']
];
die(json_encode($arr)); // 輸出: [{"id":1,"name":"zhdc"},{"id":2,"name":"\u5c0f\u6731"}]
}
import java.io.*;
import java.net.*;
public class JsonHttpClient {
public static void main(String[] args) {
String urlStr = "https://127.0.0.6/?c=json";
HttpURLConnection conn = null;
BufferedReader reader = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.setRequestProperty("Accept", "application/json");
int responseCode = conn.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
throw new IOException("HTTP error code: " + responseCode);
}
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuilder json = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
json.append(line);
}
System.out.println("原始 JSON: " + json);
// 此處可接入 Jackson/Gson 解析為對象
// List users = new ObjectMapper().readValue(json.toString(), new TypeReference<>() {});
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) try { reader.close(); } catch (IOException ignored) {}
if (conn != null) conn.disconnect();
}
}
}
UTF-8,避免中文亂碼(PHP json_encode 默認輸出 Unicode 轉義)。finally 塊中關閉流與斷開連接。MalformedURLException、IOException 等。<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
// 解析
ObjectMapper mapper = new ObjectMapper();
List<User> users = mapper.readValue(json.toString(),
mapper.getTypeFactory().constructCollectionType(List.class, User.class));
for (User u : users) System.out.println(u.getId() + " - " + u.getName());
// 實體類
class User {
private int id;
private String name;
// getter/setter 省略
}
| 現象 | 可能原因 | 解決 |
|---|---|---|
| 返回 HTML 錯誤頁 | PHP 入口文件路徑錯誤或語法錯誤 | 瀏覽器直接訪問 URL 驗證 |
| 中文顯示 \uXXXX | json_encode 未設置 JSON_UNESCAPED_UNICODE | PHP 使用 json_encode($arr, JSON_UNESCAPED_UNICODE) |
| 連接超時 | 防火牆/端口未開放/IP 錯誤 | telnet/ curl 測試連通性 |