简体   繁体   English

问题收到地震JSON结果

[英]problem recived the earthquake JSON result

This Is the Error:-这是错误:-

E/QueryUtils: problem recived the earthquake JSON result
    java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.setRequestMethod(HttpURLConnectionImpl.java:606)
        at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.setRequestMethod(DelegatingHttpsURLConnection.java:113)
        at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.setRequestMethod(HttpsURLConnectionImpl.java)
        at com.example.quakereport.QueryUtils.makeHttpRequest(QueryUtils.java:92)
        at com.example.quakereport.QueryUtils.featchEarthquakeDate(QueryUtils.java:52)
        at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:64)
        at com.example.quakereport.MainActivity$EarthquakeAsyncTask.doInBackground(MainActivity.java:56)
        at android.os.AsyncTask$2.call(AsyncTask.java:304)
        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:760)

MainActivity.java主活动.java

public class MainActivity extends AppCompatActivity {
    
    private EarthquakeAdapter mAdapter;

    //URL for earthquake data from the USGS dataset
    private static final String USGS_REQUEST_URL ="https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&eventtype=earthquake&orderby=time&minmag=6&limit=10";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /** Find a refrence to the {@link ListView} in the layout*/
        ListView eathquakeListView = (ListView) findViewById(R.id.list);

        /** Create a new {@link ArrayAdapter} of earthquakes*/
       mAdapter = new EarthquakeAdapter(this,new ArrayList<Earthquake>());
        eathquakeListView.setAdapter(mAdapter);

        /** Start the AsyncTask to fetch the earthquake data*/
        EarthquakeAsyncTask task = new EarthquakeAsyncTask();
        task.execute(USGS_REQUEST_URL);

        eathquakeListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                // Find the current earthquake that was clicked on
                Earthquake currentEarthquake = mAdapter.getItem(position);
                //convert the String URL int a URI object(to pass into the intent constructor)
                Uri eathquakeuri = Uri.parse(currentEarthquake.getmUrl());
                //Create a new intent to view the earthquake URI
                Intent websiteIntent = new Intent(Intent.ACTION_SEND, eathquakeuri);

                // Send the intent to launch a new activity
                startActivity(websiteIntent);
            }
        });

    }

    private class EarthquakeAsyncTask extends AsyncTask<String, Void, List<Earthquake>>{

        protected List<Earthquake> doInBackground(String... urls) {
            /** If there is a valid list of {@link Earthquake}, then add them to the adapter's data set. This will trigger the
             * Listview to update*/
            if(urls.length<1 || urls[0] == null){
                return null;
            }
            List<Earthquake> result = QueryUtils.featchEarthquakeDate(urls[0]);
            return result;
        }

        @Override
        protected void onPostExecute(List<Earthquake> data) {
        /** Clear the adapter of previous earthquake data*/
        mAdapter.clear();

        /** If there is a valid list of {@link Earthquake}s, then add them to the adapter's dataset. THis will trigger
         * the ListVIew to update*/

        if (data != null && !data.isEmpty()){
            mAdapter.addAll(data);
        }
        }
    }

}

QueryUtils.java查询实用程序

public final class QueryUtils {

    /**
     * Sample JSON response for a USGS query
     */

    /**
     * Create a private constructor because no one should ever create a {@link QueryUtils} object.
     * This class is only meant to hold static variables and methods, which can be accessed
     * directly from the class name QueryUtils (and an object instance of QueryUtils is not needed).
     */
    private static final String LOG_TAG = QueryUtils.class.getSimpleName();
    private QueryUtils() {
    }

    /**
     * Query the USGS dataset and return a list of{@link Earthquake} objects.
     */
    public static List<Earthquake> featchEarthquakeDate(String requestUrl)
    {
        // Create URL Object
        URL url = createurl(requestUrl);

        // Perform HTTP request to the URL and recive a JSON response back
        String JSONResponse = null;
        try{
            JSONResponse = makeHttpRequest(url);
        }catch (IOException e)
        {
            Log.e(LOG_TAG,"Problem Making http equest", e);
        }
        // Extract relevent fields fom the JSON response and create a list of {@link Earthquake}s
        List<Earthquake> earthquakes = extractFeatureFromJson(JSONResponse);

        //Return the list of {@link Earthquake}s
        return earthquakes;
    }
    /**
     * Return new URL from object from the given string URL
     */

    private static URL createurl(String stringURL){
        URL url = null;
        try {
            url = new URL(stringURL);
        }catch (MalformedURLException e){
            Log.e(LOG_TAG,"problem building the url", e);
        }
        return url;
    }

    /**
     * Make an HTTP request to the given URL and return a string as the response.
     * */
    private static 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{
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000/* millisecond*/);
            urlConnection.setConnectTimeout(15000 /*milisecond*/);
            urlConnection.setRequestMethod("Get");
            urlConnection.connect();

            //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);
            }else {
                Log.e(LOG_TAG,"Error Response code" + urlConnection.getResponseCode());
            }

        }catch (IOException e){
            Log.e(LOG_TAG,"problem recived the earthquake JSON result",e);
        }finally {
            if (urlConnection!=null)
            {
                urlConnection.disconnect();
            }
            if (inputStream!=null){
                /*
                  Closing the input Stream could throw an IOException, which is why the makeHttpRequest(URL url) method
                  signature specific than an IOException could be thrown.
                 */
                inputStream.close();
            }
        }
        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException{
        StringBuilder output = new StringBuilder();
        if (inputStream != null){
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null){
                output.append(line);
                line = reader.readLine();
            }
        }
        return output.toString();
    }

    /**
     * Return a list of {@link Earthquake} objects that has been built up from
     * parsing a JSON response.
     */
    private static List<Earthquake> extractFeatureFromJson(String eartheuakeJSON) {

        // If the JSON string is empity or null, then return early.
        if (TextUtils.isEmpty(eartheuakeJSON))
        {
            return null;
        }

        // Create an empty ArrayList that we can start adding earthquakes to
        List<Earthquake> earthquakes = new ArrayList<Earthquake>();

        // Try to parse the JSON response string. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

           // create a JSONObject from the JSON response string
            JSONObject baseJsonResponse = new JSONObject(eartheuakeJSON);

            // Extract the JSONArray associated with the key called "features", which represent a list of features(or earthquakes).
            JSONArray earthquakeArray = baseJsonResponse.getJSONArray("features");

            // For each earthquake in the earthquakeArray, create an {@link Earthquake} object
            for (int i = 0; i < earthquakeArray.length(); i++) {
                JSONObject currentEarthquake = earthquakeArray.getJSONObject(i);

                // For a given earthquake, extract the JSONObject associated with the key called "properties", which represent a
                // list of all properties for the earthquake.
                JSONObject properties = currentEarthquake.getJSONObject("properties");
                // Extract the value for the key called "mag"
                Double magnitude = properties.getDouble("mag");
                // Extract the value for the key called "place"
                String location = properties.getString("place");
                // Extract the value for the key called "time"
                long time = properties.getLong("time");
                // Extract the value for the key called "url"
                String url = properties.getString("url");

                // Create a new {@link Earthquake} object with the magnitude,locaton,time, and url
                // from the JSON response
                Earthquake earthquake = new Earthquake(magnitude, location, time,url);
                // Add the new {@link Earthquake} to the list of earthquakes.
                earthquakes.add(earthquake);
            }

        } catch (JSONException e) {
            // If an error is thrown when executing any of the above statements in the "try" block,
            // catch the exception here, so the app doesn't crash. Print a log message
            // with the message from the exception.
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }
        // Return the list of earthquakes
        return earthquakes;
    }

}

Earthquake.java地震.java

package com.example.quakereport;

import android.content.Context;

public class Earthquake {

    private Double mMagnitude;
    private String mLocation;
    private String mDate;
    private long mTimeInMillisecond;
    private String mUrl;

    public Earthquake(Double Magnitude, String Location, long TimeInMIllisecond, String Url) {
        mMagnitude = Magnitude;
        mLocation = Location;
        mTimeInMillisecond = TimeInMIllisecond;
        mUrl = Url;
    }

    public Double getmMagnitude() {
        return mMagnitude;
    }

    public String getmLocation() {
        return mLocation;
    }


    public String getmUrl() {
        return mUrl;
    }

    public long getmTimeInMillisecond() {
        return mTimeInMillisecond;
    }
}

EartquakeAdapter.java地震适配器.java

public class EarthquakeAdapter extends ArrayAdapter<Earthquake> {
    private static  final String LOCATION_SEPARATOR = "of";
    public EarthquakeAdapter (Context context, List<Earthquake> place)
    {
        super(context,0,place);
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        View listItemView = convertView;
        if (listItemView == null)
        {
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.earthquake_list_item,parent,false);

        }

        Earthquake currentEarthQuake = getItem(position);

        TextView magnitude = (TextView) listItemView.findViewById(R.id.magnitude);
        // Formate The Magnitude to show 1 decimal place
        String formattedMaginitude = formatedMagnitude(currentEarthQuake.getmMagnitude());
        magnitude.setText(formattedMaginitude);

        //Set the prope background color on the magnitude circle.
        // Fetch the background fom the Textview, which is a GadientDrawable.

        GradientDrawable maginitudeCircle = (GradientDrawable) magnitude.getBackground();
        // Get the appropriate background color based on the current earthquake magnitude

        int magnitudeColor = getMagnitudeColor(currentEarthQuake.getmMagnitude());
        // Set the color on the magnitude cicle

        maginitudeCircle.setColor(magnitudeColor);

        String originallocation = currentEarthQuake.getmLocation();
        String primaryLocation;
        String locationOffset;

        if(originallocation.contains(LOCATION_SEPARATOR))
        {
            String[] parts = originallocation.split(LOCATION_SEPARATOR);
            locationOffset = parts[0] + LOCATION_SEPARATOR;
            primaryLocation = parts[1];
        }else {
            locationOffset= getContext().getString(R.string.near_the);
            primaryLocation = originallocation;
        }

        TextView primarrylocation = (TextView) listItemView.findViewById(R.id.location_primarry);
        primarrylocation.setText(primaryLocation);

        TextView locationOffsetView = (TextView) listItemView.findViewById(R.id.location_offset);
        locationOffsetView .setText(locationOffset);

//        TextView locationView = (TextView) listItemView.findViewById(R.id.location_primarry);
//        locationView.setText(currentEarthQuake.getmLocation());

        Date dateObject = new Date(currentEarthQuake.getmTimeInMillisecond());

        TextView dateView = (TextView) listItemView.findViewById(R.id.date);
        // Fomate the date string (ex "Mar 3, 1995")
        String formattedDate = formatDate(dateObject);
        dateView.setText(formattedDate);

        TextView timeView = (TextView) listItemView.findViewById(R.id.time);
        String formattedtime = formatTime(dateObject);
        timeView.setText(formattedtime);


        return listItemView;
    }

    private int getMagnitudeColor(double magnitude)
    {
        int mgnitudeColorResourceId;
        int magnitudeFloor = (int) Math.floor(magnitude);

        switch (magnitudeFloor)
        {
            case 0:
            case 1:
                mgnitudeColorResourceId = R.color.magnitude1;
                break;
            case 2:
                mgnitudeColorResourceId = R.color.magnitude2;
                break;
            case 3:
                mgnitudeColorResourceId = R.color.magnitude3;
                break;
            case 4:
                mgnitudeColorResourceId = R.color.magnitude4;
                break;
            case 5:
                mgnitudeColorResourceId = R.color.magnitude5;
                break;
            case 6:
                mgnitudeColorResourceId = R.color.magnitude6;
                break;
            case 7:
                mgnitudeColorResourceId = R.color.magnitude7;
                break;
            case 8:
                mgnitudeColorResourceId = R.color.magnitude8;
                break;
            case 9:
                mgnitudeColorResourceId = R.color.magnitude9;
                break;
            default:
                mgnitudeColorResourceId = R.color.magnitude10plus;
                break;

        }
        return ContextCompat.getColor(getContext(),mgnitudeColorResourceId);
    }

    private String formatDate(Date dateObject){
        SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd, yyyy");
        return dateFormat.format(dateObject);
    }

    private  String formatTime (Date dateObject){
        SimpleDateFormat timeFormate = new SimpleDateFormat("h:mm a");
        return timeFormate.format(dateObject);
    }
    private  String formatedMagnitude(double magnitude){
        DecimalFormat magnitudeFormate = new DecimalFormat("0.0");
        return  magnitudeFormate.format(magnitude);
    }
}

In File: QueryUtils.java You need to change this line of code在文件:QueryUtils.java 中需要更改这行代码

urlConnection.setRequestMethod("Get");

To this one对这个

urlConnection.setRequestMethod("GET");

The error message explains it:错误消息解释了它:

This Is the Error:- E/QueryUtils: problem recived the earthquake JSON result java.net.ProtocolException: Expected one of [OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, PATCH] but was Get at这是错误:- E/QueryUtils:问题收到了地震 JSON 结果 java.net.ProtocolException:应为 [OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、PATCH] 之一但在

It expected GET but it was Get它期望 GET 但它是 Get

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM