我正在尝试从URL中请求数据,该URL取决于搜索的经纬度。到目前为止,这是我的方法,但是在使用搜索参数构建URL时遇到问题;
double latitude = extras.getDouble("latitude");
double longitude = extras.getDouble("longitude");
这是上次活动的结果
这是我的地图活动方法,将在这里提取尚未发出请求的数据,因为我想先正确获取网址
public void getApiData() {
// CMPTODO: build URI
/**
* built a URL with the lat/lng passed from prev activity
*/
String lat = String.valueOf(latitude);
String lng = String.valueOf(longitude);
Uri builtUri = Uri.parse(API_URL).buildUpon()
.appendQueryParameter("lat", lat)
.appendQueryParameter("lng", lng)
.build();
URL urlApi = new URL(builtUri.toString());
//TODO: fetch API data
// TODO: Search prefs adjust lat and long to address in JSON URL.
if (URLUtil.isValidUrl(builtUri)){
}else {
}
}
}
SideNote我是Android Dev的新手,所以我可能会以错误的方式进行操作。任何建议都欢迎
URL
public static final String API_URL= "https://data.police.uk/api/crimes-at-location?date=2017-02&lat=52.629729&lng=-1.131592";
答案 0 :(得分:1)
您需要将new URL(builtUri.toString());
包装在 try - catch
块内,因为new URL(builtUri.toString());
可能会抛出MalformedURLException
MalformedURLException
抛出该异常指示URL格式错误。在规范字符串中找不到合法协议,或者无法解析该字符串。
尝试一下
URL urlApi;
try {
urlApi = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
答案 1 :(得分:1)
请遵循以下步骤
String URL = YOUR_API_URL;
Uri.Builder builder = Uri.parse(URL).buildUpon();
builder.appendQueryParameter("value", your_value);
URL=builder.build().toString();
答案 2 :(得分:0)
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS).build();
final Request.Builder builder = new Request.Builder();
HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
urlBuilder.addEncodedQueryParameter("lat", lat)
urlBuilder.addEncodedQueryParameter("lng", lng)
builder.url(urlBuilder.build().toString());
client.newCall(builder.build())