我有一个班级
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.lang.Exception;
import java.net.HttpURLConnection;
public class HttpURLConnectionExample {
private final String USER_AGENT = "Mozilla 5.0";
// HTTP GET request
public ArrayList<dispencer> sendGet() throws Exception {
String url = "http://192.168.1.9";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
ArrayList<dispencer> dispList = new ArrayList<dispencer>();
String[] strRows = response.toString().split("@");
for (int i= 0; i <strRows.length; i++) {
dispencer disp = new dispencer(strRows[i]);
if (!disp.isOk) continue;
dispList.add(disp);
System.out.println(disp.indirizzo);
}
return dispList;
}
}
我这样称呼方法sendGet
。
HttpURLConnectionExample httpFnd= new HttpURLConnectionExample();
ArrayList<dispencer> listAr = new ArrayList<dispencer>();
try{
listAr = httpFnd.sendGet();
}
catch (Exception Exception){
fndLayout.setVisibility(View.GONE);
System.out.println("exception handled");
}
每当我尝试调用 sendGet 时,我总是会处理消息异常并且永远不会收到我的arrayList
,就像连接从未建立一样。
当我调用该方法时,我也会收到此错误
D / NetworkSecurityConfig:未使用指定的网络安全配置 平台默认
,这是我的问题的原因吗?
感谢您的帮助。
编辑我看到我需要使用asyncTask来预防异常Andy建议我如何实现它?
答案 0 :(得分:0)
试试这个:
class Loading extends AsyncTask {
@Override
protected Void doInBackground( Void... arg0)
{
// your code here
return null;
}
@Override
protected void onPreExecute()
{
//your code here
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result)
{
//your code here
super.onPostExecute(result);
}
}//Loading
您是否记得在AndroidManifest.xml中添加此行:
<uses-permission android:name="android.permission.INTERNET"/>
和
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />