您的位置:首页 > 理论基础 > 计算机网络

通过HttpClient获取服务器接口json数据已及解析

2015-11-12 16:17 901 查看

1.获取服务器接口数据方法:记得导入httpclient包

http://download.csdn.net/detail/china1988s/3791514
public static String getdata(String url, List<NameValuePair> params) {
String tag = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,"utf-8");
post.setEntity(entity);
try {
HttpResponse httpResponse = httpClient.execute(post);
tag = "get string false";
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity2 = httpResponse.getEntity();
tag=EntityUtils.toString(entity2);
//tag = Decodtool.decodeUnicode(URLDecoder.decode(EntityUtils.toString(entity2, "uft-8"), "utf-8"));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return tag;

}


2.通过Gson解析:记得导入Gson包

public static void main(String[] args) {

String data = getdata();
System.out.println(parase(data).toString());
}

private static String getdata() {
String url = "http://192.168.2.171:9898/Service_Resource.ashx";
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("method", "GetAll"));
return NetworkUtil.getdata(url, params);
}

private static ArrayList<ResourceBean> parase(String data) {
Gson gson = new Gson();
JSONObject jsonObject = JSONObject.fromObject(data);
String datapart = jsonObject.getString("data");
Type type = new TypeToken<ArrayList<ResourceBean>>() {}.getType();
ArrayList<ResourceBean> resourcebeans = gson.fromJson(datapart, type);
return resourcebeans;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: