我想在我的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