【发布时间】:2012-11-23 07:21:17
【问题描述】:
我正在尝试从 java android 程序连接到 http 网站。 我正在尝试这段代码。但显然,代码没有通过“client.execute()”语句。 我在执行后评论了一个 return 语句,但它没有通过。 我错过了什么吗?
我尝试了几乎相同的代码,但它不起作用,所以我复制了与 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 请求都应该在 Thread UI 之外运行。使用 AsyncTask。
-
嘿,是的,我只是从活动中打电话。但即使我从一个活动中调用,它应该工作得很好,对吧?我已经准备好了代码,但是这一条语句导致了问题。
-
在这一行,
in =new BufferedReader(new InputStreamReader(response.getEntity().getContent()));和 e.printStackTrace 上放置断点。运行代码时会发生什么? -
@JS_VIPER 在 Android Honeycomb 或更高版本上,您应该使用另一个线程来执行 HTTP 请求。查看 AsyncTask 文档:developer.android.com/reference/android/os/AsyncTask.html
标签: java android web-services java-server