1. 代码
/** * * 1. 基于Java接口的HttpURLConnection实现 * * 首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面, * 也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。 * 因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。 * HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。 */ package home.lee.httpjava; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import org.apache.http.HttpStatus; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.StrictMode; import android.text.Html; import android.text.method.ScrollingMovementMethod; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener{ // private static final String URL_PATH1 = "http://www.baidu.com";//"http://192.168.1.100:9000/00.Java/02.Android/01.Sum/index.html"; // private static final String URL_PATH2 = "http://192.168.1.100:9000/00.Java/02.Android/01.Sum/html5.png"; private Button getURLConnectionBtn; private Button postURLConnectionBtn; private TextView result; private URL url1; private HttpURLConnection httpURLConnection; private InputStream inputStream = null; private BufferedReader bufferedReader = null; private String line; private ImageView image; private ByteArrayOutputStream outputStream; private int len; private byte[] data; private Bitmap bitmap; private EditText inputURL; private String URL = ""; private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //for 4.0 up ver. INTERNET permission bug android4verNetworkExceptionMethod(); init(); } private void android4verNetworkExceptionMethod() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() .penaltyDeath() .build()); } private void getDataHttpURLConnection() { //可见 result.setVisibility(View.VISIBLE); result.setText(""); try { url1 = new URL("http://" + URL); httpURLConnection = (HttpURLConnection)url1.openConnection(); //对请求的属性进行一些设置 //设置输入流 httpURLConnection.setDoInput(true); httpURLConnection.setConnectTimeout(3 * 1000); //GET请求不能使用缓存 httpURLConnection.setUseCaches(false); //设置请求方式为GET httpURLConnection.setRequestMethod("GET"); System.out.println("Response Code is " + httpURLConnection.getResponseCode()); if(httpURLConnection.getResponseCode() == HttpStatus.SC_OK){ //获得输入流 inputStream = httpURLConnection.getInputStream(); bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); line = ""; while((line = bufferedReader.readLine()) != null){ result.append(line + "
"); } } } catch (MalformedURLException e) { System.out.println("Mal"); e.printStackTrace(); } catch (IOException e) {//DNS解析错误-UnknownHostException System.out.println("IOE"); result.setVisibility(View.INVISIBLE); e.printStackTrace(); } finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } httpURLConnection.disconnect(); } } } private void postDataHttpURLConnection() { //隐藏 result.setVisibility(View.INVISIBLE); try { url1 = new URL("http://" + URL); httpURLConnection = (HttpURLConnection)url1.openConnection(); //对请求的属性进行一些设置 //设置输入流 和输出流 httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setConnectTimeout(3 * 1000); //GET请求不能使用缓存 httpURLConnection.setUseCaches(false); //设置请求方式为GET httpURLConnection.setRequestMethod("POST"); if(httpURLConnection.getResponseCode() == HttpStatus.SC_OK){ //获得输入流和输出流 inputStream = httpURLConnection.getInputStream(); outputStream = new ByteArrayOutputStream(); len = 0; byte[] buffer = new byte[1024]; while((len = inputStream.read(buffer)) != -1){ outputStream.write(buffer, 0, len); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(inputStream != null){ try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } httpURLConnection.disconnect(); } } if(data != null){ data = outputStream.toByteArray(); bitmap = BitmapFactory.decodeByteArray(data, 0, data.length); image.setImageBitmap(bitmap); } } private void init() { result = (TextView)findViewById(R.id.textview); //隐藏 result.setVisibility(View.INVISIBLE); result.setMovementMethod(ScrollingMovementMethod.getInstance()); inputURL = (EditText)findViewById(R.id.edittext); image = (ImageView)findViewById(R.id.imageview); getURLConnectionBtn = (Button)findViewById(R.id.button1); postURLConnectionBtn = (Button)findViewById(R.id.button2); getURLConnectionBtn.setOnClickListener(this); postURLConnectionBtn.setOnClickListener(this); webView = (WebView)findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.button1: URL = inputURL.getText().toString(); System.out.println("URL GET-->" + URL); if(!URL.trim().equals("")){ getDataHttpURLConnection(); innerWebView(); }else{ inputURL.setError(Html.fromHtml("<font color='red'>Please enter a formal Get URL!</font>")); } break; case R.id.button2: URL = inputURL.getText().toString(); System.out.println("URL POST-->" + URL); if(!URL.trim().equals("")){ postDataHttpURLConnection(); innerWebView(); }else{ inputURL.setError(Html.fromHtml("<font color='red'>Please enter a formal Post URL!</font>")); } break; default: break; } } private void innerWebView() { webView.loadUrl("http://" + URL); webView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); //在当前的webview中跳转到新的url //获得网址 inputURL.setText(url); return true; } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){ webView.goBack(); return true; } return super.onKeyDown(keyCode, event); } }
2. 效果
代码下载