GetResponseCode for Android development throws an exception
I am trying to develop Android today to parse the json data returned by the server on the client. However, when I fail to read the value while parsing the json data, I perform a series of debugging and find that in the following code segment
Try {
URL url = new URL (url_path );
HttpURLConnection connection = (HttpURLConnection) url. openConnection ();
Connection. setConnectTimeout (3000 );
Connection. setRequestMethod (GET );
Connection. setDoInput (true); // input stream
Int code = connection. getResponseCode ();
If (code = 200) {// indicates that the server is ready
Return changeInputStream (connection. getInputStream ());
}
} Catch (Exception e ){
// TODO: handle exception
}
There is no response when connecting to the server, that is, the connection. when getResponseCode () is returned, a null value will be returned. When the url check is complete and there is no error, it will be confused. After querying the information, you will know
Calling the network operation method of this class in MainActivity may cause some activity problems. Google has added a class: StrictMode since Android. This class changes the way the network is accessed.
StrictMode is usually used to capture problems arising from interactions between disk access or network access and the main process, because in the main process, UI operations and the execution of some actions are most often used, conflicts may occur between them. Detaching disk access and network access from the main thread can make disk or network access smoother and improve response and user experience.
There are two ways to solve this problem,
First, the method is put into the new thread:
New Thread ()
{
Your method ....
}. Start;
Method 2
To do this, add the following code to MainActivity:
StrictMode. setThreadPolicy (new
StrictMode. ThreadPolicy. Builder (). detectDiskReads (). detectDiskWrites (). detectNetwork (). penaltyLog (). build ());
StrictMode. setVmPolicy (
New StrictMode. VmPolicy. Builder (). detectLeakedSqlLiteObjects (). detectLeakedClosableObjects (). penaltyLog (). penaltyDeath (). build ());
In the configuration file, set the minimum SDK level to 11.