Android上的HTTP基本授权网络问题

时间:2016-01-09 06:37:53

标签: java android rest networking android-studio

我在使用Android的Ragic查询数据库时遇到问题。我已经成功地在Eclipse中创建了一个程序,用于查询在线数据库并下载所有JSONS,将它们转换为对象,然后将它们放入ArrayList中。不幸的是,我在尝试使用Android中完全相同的代码下载相同的数据时遇到了问题。我已经添加了互联网权限(如AndroidManifest.xml中所示)。代码编译和全部,但抛出了MapsActivity.java文件末尾的NullPointerException(" RUNTIME EXCEPTION / ALLDOWNLOADEXCEPTIONS")。这是问题所在,但我不知道它是什么造成的。请帮助。

这是MapsActivity.java:

package com.main.parcaretestversion;

import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.*;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}


/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

    ArrayList<ParkingSpot> list = init();

    System.exit(0);
    for (ParkingSpot spot: list) {
        PolygonOptions rectOptions = new PolygonOptions()
                .addAll(spot.getArrayListLatLngDefault());
        if (spot.getStatus()) {
            rectOptions.fillColor(Color.GREEN);
        } else {
            rectOptions.fillColor(Color.RED);
        }
        Polygon polygon = mMap.addPolygon(rectOptions);
    }
}
public ArrayList<ParkingSpot> format(String input) {
    ArrayList<ParkingSpot> list = new ArrayList<ParkingSpot>();
    JsonElement root = new JsonParser().parse(input);
    for (int i = 0; i <= 9; i++) {
        String uid = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("ID").getAsString();
        String coordinate1 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 1").getAsString();
        String coordinate2 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 2").getAsString();
        String coordinate3 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 3").getAsString();
        String coordinate4 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 4").getAsString();
        String statusTemp = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Status").getAsString();
        boolean status;
        if (statusTemp.equals("true")) {
            status = true;
        } else {
            status = false;
        }
        list.add(new ParkingSpot(uid, status, new LatLong(coordinate1), new LatLong(coordinate2), new LatLong(coordinate3), new LatLong(coordinate4)));
    }
    return list;
}
public ArrayList<ParkingSpot> init() {
    String apiKey = "some api key";
    try {
        //
        URL url = new URL("https://api.ragic.com/some username/some sheet/1");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);

        connection.setRequestProperty("Authorization", "Basic " + apiKey);
        InputStream content = (InputStream) connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
        String uglyJson = "";
        for (String line; (line = reader.readLine()) != null; ) {
            uglyJson += line;
        }
        ArrayList<ParkingSpot> list = format(uglyJson);
        throw new NullPointerException(uglyJson);
        //return list;
    } catch (MalformedURLException e) {
        throw new NullPointerException("MALFORUMED URL EXCEPTION");
    } catch (RuntimeException allDownloadExceptions) {
        throw new NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS");
    } catch (ProtocolException e) {
        throw new NullPointerException("PROTOCOL EXCEPTION");
    } catch (IOException e) {
        throw new NullPointerException("IO EXCEPTION");
    }
}
}

这是AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<!--
     The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
     Google Maps Android API v2, but you must specify either coarse or fine
     location permissions for the 'MyLocation' functionality. 
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/. 
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <activity
        android:name=".MapsActivity"
        android:label="@string/title_activity_maps">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

1 个答案:

答案 0 :(得分:1)

在mainActivity中使用asyncTasks。

例如。

private class LongOperation extends AsyncTask<String, Void, ArrayList> {
        @Override
        protected ArrayList doInBackground(String... params) {
               URL url = new URL("https://api.ragic.com/some username/some sheet/1");

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setDoOutput(true);

    connection.setRequestProperty("Authorization", "Basic " + apiKey);
    InputStream content = (InputStream) connection.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String uglyJson = "";
    for (String line; (line = reader.readLine()) != null; ) {
        uglyJson += line;
    }
    ArrayList<ParkingSpot> list = format(uglyJson);
    throw new NullPointerException(uglyJson);
    return list;
            }



        @Override
        protected void onPostExecute(ArrayList result) {
            //Handle result here.
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }


   }

现在打电话给这个电话

   new LongOperation().execute(); 

希望它会有所帮助