如何让Android获得网页上的数据
请问,如何让Android获得网页上的数据,就是让网页上的,或者说是web服务器的某一个变量的值被Android获取,并保存到Android的一个变量之中,Servlet...
请问,如何让Android获得网页上的数据,就是让网页上的,或者说是web服务器的某一个变量的值被Android获取,并保存到Android的一个变量之中,Servlet的doget和httpget应该怎么写
展开
2个回答
展开全部
例子来自于android学习手册,android学习手册包含9个章节,108个例子,源码文档随便看,例子都是可交互,可运行,源码采用android studio目录结构,高亮显示代码,文档都采用文档结构图显示,可以快速定位。360手机助手中下载,图标上有贝壳
//第一种
/**获取参数(ArrayList<NameValuePair> nameValuePairs,String url)后post给远程服务器
* 将获得的返回结果(String)返回给调用者
* 本函数适用于查询数量较少的时候
*/
public String posturl(ArrayList<NameValuePair> nameValuePairs,String url){
String result = "";
String tmp= "";
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
return "Fail to establish http connection!";
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
tmp=sb.toString();
}catch(Exception e){
return "Fail to convert net stream!";
}
try{
JSONArray jArray = new JSONArray(tmp);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Iterator<?> keys=json_data.keys();
while(keys.hasNext()){
result += json_data.getString(keys.next().toString());
}
}
}catch(JSONException e){
return "The URL you post is wrong!";
}
return result;
}
//第一种
/**获取参数(ArrayList<NameValuePair> nameValuePairs,String url)后post给远程服务器
* 将获得的返回结果(String)返回给调用者
* 本函数适用于查询数量较少的时候
*/
public String posturl(ArrayList<NameValuePair> nameValuePairs,String url){
String result = "";
String tmp= "";
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
return "Fail to establish http connection!";
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
tmp=sb.toString();
}catch(Exception e){
return "Fail to convert net stream!";
}
try{
JSONArray jArray = new JSONArray(tmp);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Iterator<?> keys=json_data.keys();
while(keys.hasNext()){
result += json_data.getString(keys.next().toString());
}
}
}catch(JSONException e){
return "The URL you post is wrong!";
}
return result;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询