我想从java android程序连接到http网站。 我正在试着这段代码。但显然,代码不会通过“client.execute()”语句。 我已经在执行后评论过一个return语句,并且没有通过该语句。 我错过了什么?来自Android的http连接
我曾尝试非常相同的代码,它没有工作,所以我没有复制完全相同的代码形式Newboston,它仍然无法正常工作。
(代码来自Newboston。)
在此先感谢您。
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in=null;
String data=null;
try{
HttpClient client=new DefaultHttpClient();
URI website=new URI("http://www.mybringback.com");
HttpGet request=new HttpGet();
request.setURI(website);
HttpResponse response=client.execute(request);
// if(data==null)
// return "bfdvhf";
in =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb=new StringBuffer("");
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
sb.append(l + nl);
return "hfeuhfuie";
}
in.close();
data=sb.toString();
return data;
}finally{
if(in!=null)
{
try{
in.close();
return data;
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
你如何调用getInternetData()?从活动? 只是一个建议:任何http请求应该运行一个线程UI的外部。使用AsyncTask。 – dougcunha
嘿, 是的,我只是从活动打电话。但即使我从一项活动中打电话,它应该可以正常工作吗? 我已经准备好了我的代码,但是这一条语句导致了一个问题。 –
在这行上放置断点,'in = new BufferedReader(new InputStreamReader(response.getEntity()。getContent()));'和e.printStackTrace在catch中。当你运行你的代码时会发生什么? – Simon