使用Httpclient
,如何解析json数据。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httppost);
apiResponse = new ApiResponse();
apiResponse.code = httpResponse.getStatusLine().getStatusCode();
if (apiResponse.code == HttpStatus.SC_OK)
{
httpentity = httpResponse.getEntity();
apiResponse.response = new String(EntityUtils.toString(httpentity));
}
答案 0 :(得分:1)
检索任何基于API的模型数据的第一步是执行网络请求以检索表示我们要使用的基础数据的JSON响应
{
“business”:[
{
"id": "yelp-tropisueno",
"name" : "Tropisueno",
"display_phone": "+1-415-908-3801",
"image_url": "http://anyurl/ms.jpg",
}
] }
让我们创建一个Java类,它将在我们的应用程序中充当商业模型:
public class Business {
private String id;
private String name;
private String phone;
private String imageUrl;
public String getName() {
return this.name;
}
public String getPhone() {
return this.phone;
}
public String getImageUrl() {
return this.imageUrl;
}}
我们需要添加一个方法来管理JSON字典反序列化为一个填充的Business对象:
public class Business { public static Business fromJson(JSONObject jsonObject) {
Business b = new Business();
try {
b.id = jsonObject.getString("id");
b.name = jsonObject.getString("name");
b.phone = jsonObject.getString("display_phone");
b.imageUrl = jsonObject.getString("image_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return b; }}
并成功创建Business with Business.fromJson(json)。但是,在API响应中,我们实际上在数组中获得了业务JSON的集合。因此,理想情况下,我们还可以轻松地将一组业务处理为Business对象的ArrayList。这可能看起来像:
public class Business { public static ArrayList<Business> fromJson(JSONArray jsonArray) {
ArrayList<Business> businesses = new ArrayList<Business>(jsonArray.length());
for (int i=0; i < jsonArray.length(); i++) {
JSONObject businessJson = null;
try {
businessJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
Business business = Business.fromJson(businessJson);
if (business != null) {
businesses.add(business);
}
}
return businesses; }}
有了这个,我们现在可以传递一个业务json数据的JSONArray并轻松处理到一个很好的ArrayList对象,以便在我们的应用程序中使用Business.fromJson(myJsonArray)。
JSONArray enterprisesJson = apiResponse.response.getJSONArray(“business”);
ArrayList enterprises = Business.fromJson(businessesJson);
答案 1 :(得分:0)
不建议使用HttpClient使用HttpUrlConnection:
ANALYZE
您可以使用:try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = null;
OutputStream os = null;
try {
conn.setReadTimeout(_readTimeout);
conn.setConnectTimeout(_connectTimeout);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Date", _date );
if(mbIsGET){// Get Request
conn.setRequestMethod("GET");
}else{ // Post Request
conn.setRequestMethod("POST");
conn.setDoOutput(true);
os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(_PostRequest);
writer.flush();
writer.close();
os.close();
}
conn.connect();
int code = conn.getResponseCode();
if (code == HttpURLConnection.HTTP_OK) {
//do something with response
is = conn.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
inputStr = responseStrBuilder.toString();
if(mbIsGET){Result = parseResponseGET(inputStr);}
else{Result = parseResponsePOST(inputStr);}
}
} catch (ProtocolException e) {
e.printStackTrace();
} finally {
//clean up
try {
if (is != null) is.close();
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
答案 2 :(得分:-1)
使用以下mehtod进行json解析
public static ApiResponse doPost (String url,ArrayList params)抛出异常{ ApiResponse apiResponse = null;
HttpEntity httpentity = null;
Log.print("WebInterface :: dopost() :; URL", url);
Log.debug("WebInterface :: dopost() :; URL", url);
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpclient.execute(httppost);
apiResponse = new ApiResponse();
apiResponse.code = httpResponse.getStatusLine().getStatusCode();
if (apiResponse.code == HttpStatus.SC_OK)
{
httpentity = httpResponse.getEntity();
apiResponse.response = new String(EntityUtils.toString(httpentity));
}
Log.print("WebInterface :: dopost() :: ", " Code ::: " + apiResponse.code + " <BR/> Response :: " + apiResponse.response);
Log.debug("WebInterface :: dopost() :: ", " Code ::: " + apiResponse.code + " <BR/> Response :: " + apiResponse.response);
// release
httpentity = null;
httpResponse = null;
httppost = null;
httpclient = null;
}
catch (SocketException e)
{
e.printStackTrace();
}
return apiResponse;
}