gpt4 book ai didi

android - 来自 Mapquest 的不正确的 JSON 响应 - Android 应用程序

转载 作者:可可西里 更新时间:2023-11-01 11:40:55 25 4
gpt4 key购买 nike

我正在尝试使用 mapquest api 将 JSON 对象从 mapquest 获取到 Android 应用程序中。 JSON请求规范如下。

POST URL:
http://www.mapquestapi.com/directions/v2/route?key=[YOUR_KEY_HERE]
POST BODY:
{
locations:[
"State College, PA",
"Lancaster, PA"
]
}

以下代码成功建立连接,但是mapquest的响应不正确。

URL url_mapquest = new URL("http://www.mapquestapi.com/directions/v2/route?key=xxxxxxxxxxxx");

HttpURLConnection connection = (HttpURLConnection) url_mapquest.openConnection();
String urlParameters = "None";
connection.setRequestMethod("POST");
connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
connection.setDoOutput(true);

JSONObject jsonParam = new JSONObject();
try {
JSONArray list = new JSONArray();
list.put("State College, PA");
list.put("Lancaster, PA");
jsonParam.put("locations", list);
} catch (JSONException e) {
e.printStackTrace();
}

System.out.println("JSON String: " + jsonParam.toString());

DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(jsonParam.toString());
dStream.flush();
dStream.close();
int responseCode = connection.getResponseCode();

System.out.println("\nSending 'POST' request to URL : " + url_mapquest);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

final StringBuilder output_Mars = new StringBuilder("Request URL : " + url_mapquest);
output_Mars.append(System.getProperty("line.separator") + "Request Parameters : " + urlParameters);
output_Mars.append(System.getProperty("line.separator") + "Response Code : " + responseCode);
output_Mars.append(System.getProperty("line.separator") + "Type : " + "POST");

String line = "";
StringBuilder responseOutput = new StringBuilder();

if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
System.out.println("output===============" + br);
while ((line = br.readLine()) != null) {
responseOutput.append(line);
}
br.close();
} else {
responseOutput.append("Response Code 403 Forbidden");
}

下面是从android模拟器抓取的错误响应

enter image description here

代码中可能有什么问题?


引用资料:

最佳答案

如何将以下内容添加到连接属性

connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");

模拟器响应中的以下注释表明应用程序可能没有正确接收 JSON 对象。

A JSONObject text must begin with a '{' at character 0 

关于android - 来自 Mapquest 的不正确的 JSON 响应 - Android 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36142721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com