2016-03-21 39 views
2

我想从使用mapquest API的mapquest获取JSON对象到Android应用中。 JSON请求规格如下。Mapquest不正确的JSON响应 - Android应用

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

捕捉什么可能是错误的代码?


参考文献:

+4

有没有什么办法可以显示JSON(jsonParam.toString())你发布到API? – Ultradiv

+0

首先,它看起来像没有包含所需的路由密钥,但它有助于查看Ultradiv询问的JSON。 – RScottCarson

+0

@Ultradiv(jsonParam.toString()是{“locations”:[“State College,PA”,“Lancaster,PA”]} –

回答

2

如何加入以下连接属性

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

在模拟器响应下面的评论表明,应用程序可能无法被接受的JSON对象正确。

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