Skip to content

Commit

Permalink
检查 HTTP 响应代码
Browse files Browse the repository at this point in the history
  • Loading branch information
heyblood committed Jan 23, 2021
1 parent 4326db4 commit f095676
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
1 change: 1 addition & 0 deletions .idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 26 additions & 4 deletions app/src/main/java/com/example/soonami/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

Expand All @@ -41,12 +42,16 @@
*/
public class MainActivity extends AppCompatActivity {

/** Tag for the log messages */
/**
* Tag for the log messages
*/
public static final String LOG_TAG = MainActivity.class.getSimpleName();

/** URL to query the USGS dataset for earthquake information */
/**
* URL to query the USGS dataset for earthquake information
*/
private static final String USGS_REQUEST_URL =
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-12-01&minmagnitude=7";
"https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-01-02asdfasdf";

@Override
protected void onCreate(Bundle savedInstanceState) {
Expand Down Expand Up @@ -155,6 +160,12 @@ private URL createUrl(String stringUrl) {
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";

// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}

HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
Expand All @@ -164,7 +175,13 @@ private String makeHttpRequest(URL url) throws IOException {
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);

// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
Expand Down Expand Up @@ -202,6 +219,11 @@ private String readFromStream(InputStream inputStream) throws IOException {
* about the first earthquake from the input earthquakeJSON string.
*/
private Event extractFeatureFromJson(String earthquakeJSON) {
// If the JSON string is empty or null, then return early.
if (TextUtils.isEmpty(earthquakeJSON)) {
return null;
}

try {
JSONObject baseJsonResponse = new JSONObject(earthquakeJSON);
JSONArray featureArray = baseJsonResponse.getJSONArray("features");
Expand Down

0 comments on commit f095676

Please sign in to comment.