获取网页源码,昨天搞了一夜,你懂的。现在分享
aide吧
全部回复
仅看楼主
level 8
大家有更简洁的方法吗
//获取网页源码
package com.mycompany.myhttp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.*;
import java.io.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.*;
import org.apache.http.impl.client.*;
import java.net.*;
public class MainActivity extends Activity
{
private TextView textview;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
textview = (TextView) findViewById(R.id.textview);
new Thread(runnable).start();
textview.setText("正在获取...");
}
Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
Bundle data =msg.getData();
String val = data.getString("value");
Intent in=new Intent();
//将结果值放进urlval里
in.putExtra("urlval", val);
//跳转到第二个界面
in.setClass(MainActivity.this, MainActivity2.class);
//启动第二个界面
startActivity(in);
MainActivity.this.finish();
}
} ;
Runnable runnable = new Runnable()
{
@Override
public void run()
{
//耗时操作
String u=posturl("http://www.baidu.com/");
Message msg = new Message();
Bundle data = new Bundle();
data.putString("value", u);
msg.setData(data);
handler.sendMessage(msg);
}
} ;
public String posturl(String urlv)
{
String v="";
//根据http协议,要访问服务器上的某个网页,必须先建立一个连接,连接的参数为一个URL
try
{
URL url=new URL(urlv);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置请求方式为GET方式,就是相当于浏览器打开网页
connection.setRequestMethod("GET");
//接着设置超时时间为5秒,5秒内若连接不上,则通知用户网络连接有问题
connection.setReadTimeout(5000);
//若连接上之后,得到网络的输入流,内容就是网页源码的字节码
InputStream inStream= connection.getInputStream();
//必须将其转换为字符串才能够正确的显示给用户
ByteArrayOutputStream data=new ByteArrayOutputStream();//新建一字节数组输出流
byte[] buffer = new byte[1024];//在内存中开辟一段缓冲区,接受网络输入流
int len=0;
while ((len = inStream.read(buffer)) != -1)
{
data.write(buffer, 0, len); //缓冲区满了之后将缓冲区的内容写到输出流
}
inStream.close();
v = new String(data.toByteArray(), "utf-8");
}
catch (IOException e)
{
return "Fail to convert net stream!";
}
return v;
}
}
2015年07月26日 04点07分 1
level 8
用AndroLua一句代码搞定,http.get(url)
2015年07月26日 04点07分 2
level 13
打开浏览器-打开网页-菜单-保存网页
OK[haha][滑稽][胜利]
2015年07月26日 06点07分 4
level 11
简单的get方法
2015年07月26日 07点07分 5
level 13
有android-async-http这么好用的类库居然不用。。。。。。。
2015年07月26日 07点07分 6
不会啊
2015年07月26日 07点07分
level 7
我也搞了一个。跟你的不同,请看楼中楼
2015年07月26日 22点07分 7
package com.yzy.http; import android.app.*; import android.os.*; import android.view.*; import android.widget.*; import android.view.View.*
2015年07月26日 22点07分
1