我想在我的android应用程序中获取我的网站数据。我用下面的代码尝试了它,应用程序启动,然后在屏幕上显示加载数据的简单activity_main.xml。我附上我的代码,请指导我。在Android应用程序上获取网站数据
MainActivity.java:
package com.example.httpexample;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity
{
TextView httpStuff;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.tvHttp);
GetMethodEx test = new GetMethodEx();
String returned;
try
{
returned = test.getInternetData();
httpStuff.setText(returned);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
GetMethodEx.java:
package com.example.httpexample;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
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.hashmedia.in");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
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);
}
in.close();
data = sb.toString();
return data;
}
finally
{
if(in!=null)
{
try
{
in.close();
return data;
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
activity_main.xml中:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.httpexample.MainActivity" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/tvHttp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Loading Data" />
</ScrollView>
</LinearLayout>
你的问题是什么? – 2014-11-06 05:09:08
确切的问题是我想看到我的网站上的Android应用程序的数据,但只有空白屏幕显示没有任何信息显示。 – 2014-11-06 05:12:02
谢谢。你能建议我在哪里写这个代码?这将是一个很大的帮助。 – 2014-11-06 05:19:00