1个回答
推荐于2016-02-02
展开全部
传入网址路径,获取字符串
public static String getHtmlContent(String url) {
String htmlCode = null;
StringBuffer resultBuffer = new StringBuffer();
HttpGet request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
BufferedReader io = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
String strResult;
while((strResult = io.readLine())!=null){
resultBuffer.append(strResult);
}
htmlCode = new String(resultBuffer);
io.close();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return htmlCode;
}
解析json字符串
private String parseJson(String strResult) {
String temp = null;
try {
JSONObject jsonObj = new JSONObject(strResult).getJSONObject("weatherinfo");
temp = jsonObj.getInt("temp") + "#" +jsonObj.getString("city");
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
return temp;
}
注意事项:网络请求要异步操作
public static String getHtmlContent(String url) {
String htmlCode = null;
StringBuffer resultBuffer = new StringBuffer();
HttpGet request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse response = httpClient.execute(request);
if(response.getStatusLine().getStatusCode() == 200)
{
HttpEntity entity = response.getEntity();
BufferedReader io = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
String strResult;
while((strResult = io.readLine())!=null){
resultBuffer.append(strResult);
}
htmlCode = new String(resultBuffer);
io.close();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return htmlCode;
}
解析json字符串
private String parseJson(String strResult) {
String temp = null;
try {
JSONObject jsonObj = new JSONObject(strResult).getJSONObject("weatherinfo");
temp = jsonObj.getInt("temp") + "#" +jsonObj.getString("city");
} catch (JSONException e) {
System.out.println("Json parse error");
e.printStackTrace();
}
return temp;
}
注意事项:网络请求要异步操作
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询