我尝试从服务器读取JSON文件,但是当我将此URL传递给它时,它不返回JSON对象, 并且没有错误或异常发生,只是它返回了空字符串,我不希望这样,
这是测试的网址:http://famila1.ir/khabgah/get_khabgah_cash.php
这是我的清单文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.aqamamad.myapplication">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
下面是代码:
public class JSONDownloader
{
public String downloadURL( String strUrl )
{
String data = "";
try
{
URL url = new URL( strUrl );
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.connect();
InputStream myStream = connection.getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader( myStream ) );
StringBuilder sb = new StringBuilder();
String line;
while ( ( line = br.readLine() ) != null )
{
sb.append( line );
}
data = sb.toString();
br.close();
connection.disconnect();
myStream.close();
}
catch ( Exception e )
{
/*
*Log.i( "MatiMessage" , "error in JSONDownloader in downloadURL() -> " + e.toString() );
*/
}
return data;
}
}
有人知道这段代码有问题吗?
答案 0 :(得分:2)
public void getContent(String url) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) new URL(url).openConnection();
} catch (IOException e) {
e.printStackTrace();
}
if (conn != null) {
conn.setRequestProperty("Accept", "application/json,text/html");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Cookie", "");
try {
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
is.close();
conn.disconnect();
return sb.toString();
} catch (SocketException e) {// connection reset
Log.d(TAG, "SocketException: " + e);
return null;
} catch (Exception e) {// connection reset
Log.d(TAG, "Exception: " + e);
return null;
}
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// You get the result here
}
}.execute(null, null, null);
}
Http连接被认为是耗时的操作,因此您需要将其放入另一个线程而不是UI线程