我在做一个android项目。我为此项目使用MySQL,PHP,Android Studio。我创建一个服务器和数据库。我想在任何地方访问服务器。因此,我使用一个静态IP并添加一个端口。当我检查此端口时,我看到它是打开的,并且在任何地方都可以访问该IP。我尝试。
然后,我为JSON值创建一个表和php页面。
我的PHP页面返回以下内容:
{
"News": [
{
"NewsID": "1",
"NewsTitle": "A",
"NewsDesc": "A",
"NewsImage": "A.jpg",
"NewsDate": "2019-08-20"
}
]
}
现在,我想在android中解析此JSON值。我尝试使用基本的HTTP Request和Retrofit 2,但是我无法访问URL。我尝试其他网址,它们正在工作。但是,当我写我的IP地址时;我取空值。我不能解决这个问题。我该怎么办?
这是我在Java中的HttpHandler类:
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
然后在MainActivity类上对此进行解析:
HttpHandler hh = new HttpHandler();
String JSON = hh.makeServiceCall(url);