这里先把代码贴到这里做一个存档,写到SD卡的是一个txt文件,改成HTML格式之后会出现百度主页,但是中文是乱码,这一点先暂时不去研究了。
代码:
package com.larry.gotcha; import java.io.BufferedReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button;
public class MainActivity extends Activity { private Button requestButton = null ; private HttpResponse httpResponse = null ; private HttpEntity httpEntity = null ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestButton =(Button)findViewById(R.id.requestButton); requestButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //生成一个请求对象 HttpGet httpGet = new HttpGet("http://www.baidu.com/"); //生成客户端对象 HttpClient httpClient = new DefaultHttpClient(); //使用客户端发送请求对象 InputStream inputStream = null ; try { //execute返回一个HttpResponse类型的参数,代表服务器返回的响应 httpResponse = httpClient.execute(httpGet); //HttpResponse代表返回的响应,那么HttpEntity就代表响应的内容Obtains the message entity of this response, if any. httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent();//注意getContent()方法很常用 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String sd = Environment.getExternalStorageDirectory().getPath(); @SuppressWarnings("resource") FileWriter fw = new FileWriter( sd + "/gotcha.txt"); String line = "" ; String result = "" ; while((line = br.readLine()) != null) { result = line + result ; } System.out.println(result); fw.write(result , 0 , result.length()); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { inputStream.close(); } catch(Exception e) { e.printStackTrace(); } } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
HTTP操作顺序是:HttpGet--HttpClient--HttpResponse--HttpEntity。
这里I/O流里用的是InputStream、BufferedReader和FileWriter。
注意要在Mainifest里添加两个权限(这次忘了添加写入SD卡的权限,下午在英语课上想到了。。)
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>