<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="request btn"/><TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /></LinearLayout>
package com.oppo;import org.apache.http.HttpEntity;import org.apache.http.HttpHost;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.conn.params.ConnRouteParams;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.params.HttpParams;import android.app.Activity;import android.net.Proxy;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;public class HttpTestActivity extends Activity { protected static final String TAG = "HttpTestActivity"; private Button requestBtn; private HttpResponse httpResponse; private HttpEntity httpEntity; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); requestBtn = (Button)findViewById(R.id.btn); requestBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //擷取代理資訊 String host = Proxy.getHost(getApplicationContext()); int port = Proxy.getPort(getApplicationContext()); Log.d(TAG, "[createHttpClient] proxyHost = " + host); Log.d(TAG, "[createHttpClient] proxyPort = " + port); //設定主機http串連資訊 HttpHost httpHost = new HttpHost(host, port); HttpParams httpParams = new BasicHttpParams(); httpParams.setParameter(ConnRouteParams.DEFAULT_PROXY, httpHost); HttpGet httpGet = new HttpGet("http://www.baidu.com"); HttpClient httpClient = new DefaultHttpClient(httpParams); InputStream inputStream = null; try { httpResponse = httpClient.execute(httpGet); httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String result = ""; String line = ""; while((line = reader.readLine()) != null){ result += result + line; } System.out.println(result); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ /*try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }*/ } } }); }}
別忘了這句哦 要有intent存取權限
<uses-permission android:name="android.permission.INTERNET"/>
部落格已搬到http://marspring.mobi/