Android网络通信
Android中提供了库函数用于网络访问,同样也可以用java中的库来访问网络,如socket编程,要想让应用可以访问网络,必须赋予android.permission.INTERNET的权限,另外还需要注意,如果访问的是本地则应使用10.0.2.2这个IP来访问,否则这里的localhost会被Android当成是它本身,对于网络状态,可以通过Android提供的ConnectivityManager类中的有关属性和方法来判断,android模拟器(simulator)把它自己作为了localhost,也就是说,代码中使用localhost或者127.0.0.1来访问,都是访问模拟器自己!这是不行的!如果你想在模拟器simulator上面访问你的电脑,那么就使用android内置的IP 10.0.2.2。
在Android中,可以使用ConnectivityManager类来获取当前设备的网络状态,代码如下:
public class MainActivity extends Activity {
private Button btn;
private NetworkInfo ni;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
ni = cm.getActiveNetworkInfo();
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if( ni != null){
Toast.makeText(MainActivity.this, "成功连接 : "+ni.getTypeName(), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "未成功连接", Toast.LENGTH_SHORT).show();
}
}
});
}
}
需要在AndroidManifest.xml配置文件中加上以下的属性:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
然后观察设备会显示网络状态
WebView是用于显示Web页面的View,在Activity中,WebView可以使用任何一个浏览器简易地显示一些Web内容,它使用Webkit绘图引擎去显示页面,下面看个代码:
public class MainActivity extends Activity {
private WebView wv;
private EditText et;
private Button btn;
private ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
wv = (WebView) findViewById(R.id.webView1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(MainActivity.this
.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
wv.loadUrl(et.getText().toString());
wv.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
view.loadUrl(url);
et.setText(url);
return super.shouldOverrideUrlLoading(view, url);
}
@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if(pd == null){
pd = ProgressDialog.show(MainActivity.this, "网页装载", "Page Loading!");
}
else{
pd.show();
super.onPageStarted(view, url, favicon);
}
}
@Override
public void onPageFinished(WebView view, String url) {
if(pd != null)
pd.hide();
super.onPageFinished(view, url);
}
});
wv.setWebChromeClient(new WebChromeClient(){
@Override
public void onReceivedTitle(WebView view, String title) {
System.out.println(title);
super.onReceivedTitle(view, title);
}
@Override
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.setProgress(newProgress * 1000);
super.onProgressChanged(view, newProgress);
}
});
}
});
}
}
网络之间通信可以通过以下几种方式,下面看几个比较常用的方式,另外所有有关网络的操作必须添加权限:
HttpUrlConnectionGet
public class MainActivity extends Activity {
private HttpURLConnection conn;
private URL url;
private InputStream is;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String urlData = "http://222.27.166.105:8080/Android_Service/maidou.jsp";
try {
url = new URL(urlData);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.connect();
is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuffer sb = new StringBuffer();
while((line = br.readLine())!=null){
sb.append(line);
}
System.out.println(sb+"--------");
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
HttpPost
public class MainActivity extends Activity {
private HttpPost httpPost;
private HttpClient httpClient;
private HttpResponse httpResponse;
private UrlEncodedFormEntity encodedFormEntity;
private HttpEntity httpEntity;
private InputStream in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpPost = new HttpPost("http://222.27.166.105:8080/Android_Service/maidou.jsp");
httpClient = new DefaultHttpClient();
List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
pairs.add(new BasicNameValuePair("name", "111111111111"));
try {
encodedFormEntity = new UrlEncodedFormEntity(pairs);
httpPost.setEntity(encodedFormEntity);
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
in = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null){
sb.append(line);
}
System.out.println(sb.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Httpget
public class MainActivity extends Activity {
private HttpGet httpGet;
private HttpClient httpClient;
private HttpResponse httpResponse;
private HttpEntity httpEntity;
private InputStream in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpGet = new HttpGet("http://10.0.2.2:8080/Android_Service/maidou.jsp");
httpClient = new DefaultHttpClient();
try {
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
in = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
StringBuffer sb = new StringBuffer();
while((line = br.readLine()) != null){
sb.append(line);
}
System.out.println(sb.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
以上均要加权限如下:<uses-permissionandroid:name="android.permission.INTERNET"/>