The road to Android development and learning-experience at the beginning of Network Programming
Generally, mobile phones need to access the Internet. Generally, our browser is a webview. The following is a simple implementation of the following functions: Compile the layout of Android first:
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--><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:orientation="vertical" android:layout_margin="10dp" android:padding="10dp" tools:context="com.example.jared.webviewstudy.MainActivity"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content"> <edittext android:id="@+id/netAddress" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content"><button android:id="@+id/openNetAddress" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="0" android:text="Open" android:textallcaps="false"> <webview android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"></webview></button></edittext></linearlayout></linearlayout>
Here, an EditText is used to enter the URL, a Button is used to open the webpage, and webView is used to present the webpage. Write the following code:
package com.example.jared.webviewstudy;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.webkit.WebView;import android.webkit.WebViewClient;import android.widget.Button;import android.widget.EditText;public class MainActivity extends AppCompatActivity { private WebView myWebView; private EditText networkAddr; private Button openNetwork; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); networkAddr = (EditText)findViewById(R.id.netAddress); myWebView = (WebView)findViewById(R.id.webView); openNetwork = (Button)findViewById(R.id.openNetAddress); openNetwork.setOnClickListener(new myOnClickListener()); } class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); String networkAddress = networkAddr.getText().toString(); myWebView.loadUrl("http://"+networkAddress); } }}
There is also a permission issue:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Here, we use the setWebViewClient method to instantiate a WebViewClient and loadurl to load webpages. Run the command to see the effect:
Here I opened the addresses of Baidu and my blog. The interface was a little ugly and barely looked.
Generally, network programming is implemented through http. The first step is HttpURLConnection. This is generally provided by the official google website. There is also an HttpClient. Originally, api23 is gone now, you need to load it yourself.
Use HttpURLConnection and HttpClient first, create a project, and write the layout Code as follows:
<! -- {Cke_protected} {C} % 3C! % 2D % 2D % 3 Fxml % 20 version % 3D % 221.0% 20 encoding % 3D % 22utf-8% 22% 3F % 2D % 2D % 3E --> <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: orientation = "vertical" android: layout_margin = "10dp" tools: context = "com. example. jared. httpurlconnectionstudy. mainActivity "> <button android: id =" @ + id/sendRequest "android: text =" Send request "android: layout_width =" match_parent "android: layout_height = "wrap_content"> <scrollview android: layout_width = "match_parent" android: layout_height = "match_parent"> <textview android: id = "@ + id/response" android: layout_width = "match_parent" android: layout_height = "wrap_content"> </textview> </scrollview> </button> </linearlayout>
Here, a button is used to obtain data. Then, the http request data can be viewed by ScrollView, and more information is displayed in TextView.
Compile MainActivity, which implements HttpURLConnection and HttpClient:
package com.example.jared.httpurlconnectionstudy;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBar;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.apache.http.HttpEntity;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;import org.apache.http.util.EntityUtils;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity { private static final int SHOW_RESPONSE = 1; private Button sendRequestBtn; private TextView responseView; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_RESPONSE: String responseContent = (String)msg.obj; responseView.setText(responseContent); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.activity_main); responseView = (TextView)findViewById(R.id.response); sendRequestBtn = (Button)findViewById(R.id.sendRequest); sendRequestBtn.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.sendRequest: String url = "http://www.baidu.com"; //sendRequestWithHttpURLConnection(url); sendRequestWithHttpClient(url); break; default: break; } } } private void sendRequestWithHttpClient(final String url) { new Thread(new Runnable() { @Override public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity, "utf-8"); Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = response.toString(); mHandler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void sendRequestWithHttpURLConnection(final String url) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL mUrl = new URL(url); connection = (HttpURLConnection)mUrl.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while((line = reader.readLine()) != null) { response.append(line); } Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = response.toString(); mHandler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); }}
The HttpClient here needs to be packaged into the libs under \ sdk \ platforms \ android-23 \ optional to the project directory, and then
Add
// Apache Httpandroid { useLibrary 'org.apache.http.legacy'}// Headerdependencies { compile "org.apache.httpcomponents:httpcore:4.3.2"}
In this way, the HttpClient can be used. It is similar to loading other libraries.
The running effect is as follows:
Common Http frameworks include android-async-http, which will be used below. Download the jar package from the official website: http://loopj.com/android-async-http /. Download an httpclient jar package: http://mvnrepository.com/artifact/cz.msebera.android/httpclient/4.4.1.1.
Modify build. gradle as follows:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile files('libs/android-async-http-1.4.9.jar') compile files('libs/httpclient-4.4.1.1.jar')}
Put both packages in the libs directory. Switch to the project directory, for example:
Modify the MainActivity code and add sendRequestWithAsyncHttpClinet as follows:
private void sendRequestWithAsyncHttpClient(String url) { AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { try { String response = new String(bytes, 0, bytes.length, "UTF-8"); responseView.setText(response); }catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { } }); }
The same effect can be achieved through running. AsyncHttpClient is easy to use and much simpler than the above Code. Here we use a get method, and then convert the obtained data into a String in the onSuccess method to display it in text.
The webview and http of network programming are basically learned here. I would also like to thank my friends for reminding me that the optical Foundation will use a lot of frameworks in actual projects and you need to familiarize yourself with them. I will continue to learn more here.