android学习二十(使用HTTP协议访问网络) - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

android学习二十(使用HTTP协议访问网络)

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:55


应用HttpURLConnection
在Android上发送HTTP请求的方法一般有两种,HttpURLConnection和HttpClient,如今先进修下
 HttpURLConnection的用法。
    接下来就可以进行一些自由的定制了,比瘸黎置连接超时,攫取超时的毫秒数,以及办事器欲望获得的一些消息优等。这部分内容根据本身的实际情况进行编写,示例如下:
 起首须要获取到HttpURLConnection的实例,一般只需new 出一个URL对象,并传入目标收集的地址,然后
 URL URL=new URL("http://www.baidu.com");
 HttpURLConnection connection=( HttpURLConnection)url.openConnection();
 获得了 HttpURLConnection的实例之后,我们可以设置一下HTTP请求所应用的办法。常用的办法重要有两个,
 connection.setRequestMethod("GET");
 connection.setConnectionTimeout(8000);
 connection.setReadTimeout(8000);
 之后调用getInputStream()办法就可以获取到办事器返回的输入流了,剩下的义务就是对输入流进行攫取,如下所示:
 InputStream in=connection.getInputStream();
 最后可声调用disconnect()办法将这个HTTP连接封闭掉落,如下所示:
 connection.disconnection();
  只须要在转换的时刻将字符集指定成utf-8就可以了,如下所示:
     //要乞降响应都成功了
 下面经由过程一个具体的例子来熟悉下HttpURLConnection的用法。新建NetworkTest项目,起首修改activit_main.xml中的代码,如下所示:

<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"
    >

    <Button 
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send request"
        />

  <ScrollView 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <TextView 
            android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </ScrollView>
     
    
    
</LinearLayout>

      因为手机屏幕的空间一般都比较小,有些时刻过多的内容一屏是显示不下的,借助ScrollView控件的话就可以许可我们以滚动的情势查看屏幕外的那部分内容。别的构造中还放置了一个Button和一个TextView,Button用来发送HTTP请求,TextView用于将办事器返回的数据显示出来。接着修改MainActivity中的代码如下所示:


      在send request按钮的点击事沂攀里调用了sendRequestWithHttpURLConnection()办法,,在这个办法中先是开启了一个子线程,然后在子线程里应用HttpURLConnection发出一条HTTP请求,请求的目标地址就是百度的首页。接着应用BufferedReader对办事器返回的流进行攫取,并将结不雅存放到了一个Message对象中。这里为什么要应用Message对象呢?当然是因为子线程中无法对ui进行操作了。我们欲望可以将办事器返回的内容显示到界面上所以就创建了一个Message对象,并应用Handler将它发送出去。之后又在Handler的handMessage()办法中对这条Message进行处理,最终掏出结不雅并设置到TextView上。
在开端运行之前,还须要声明一下收集权限。修改AndroidManifest.xml中的代码,如下所示:

  if(httpResponse.getStatusCode()==200){
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jack.networktest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET"/>
    
    
    <uses-sdk
        android:minSdkVersion="13"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jack.networktest.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

运行下法度榜样,点击send request按钮,结不雅如下所示:
[img]http://img.blog.csdn.net/20150106162434587?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvajkwMzgyOTE4Mg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center
     办事器返回给我们的就是这种HTML代码,只是平日情况下浏览器都邑将这些代码解析成漂亮的网页后再展示出来。
       如不雅想要提交数据给办事器,只须要将HTTP请求的办法改成POST,并在获取输入流之前把 要提交的数据写出来即可。留意每条数据都要以键值对的情势存在,数据与数据之间用&符号隔开,比如说我们想要向办事器提交用户名和暗码,就可以如许写:
connection.setRequestMethod("POST");
package com.jack.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/*
 在Android上发送HTTP请求的方法一般有两种,HttpURLConnection和HttpClient,如今先进修下
 HttpURLConnection的用法。
 起首须要获取到HttpURLConnection的实例,一般只需new 出一个URL对象,并传入目标收集的地址,然后
 调用一下openConnection()办法即可,如下所示:
 URL URL=new URL("http://www.baidu.com");
 HttpURLConnection connection=( HttpURLConnection)url.openConnection();
 获得了 HttpURLConnection的实例之后,我们可以设置一下HTTP请求所应用的办法。常用的办法重要有两个,
 get和post。get表示欲望大年夜办事器那边获取数据,而post则表示提交数据给办事器。写法如下:
 connection.setRequestMethod("GET");
 接下来就可以进行一些自由的定制了,比瘸黎置连接超时,攫取超时的毫秒数,以及办事器欲望获得的一些消息优等。
 这部分内容根据本身的实际情况进行编写,示例如下:
 connection.setConnectionTimeout(8000);
 connection.setReadTimeout(8000);
 之后调用getInputStream()办法就可以获取到办事器返回的输入流了,剩下的义务就是对输入流进行攫取,如下所示:
 InputStream in=connection.getInputStream();
 最后可声调用disconnect()办法将这个HTTP连接封闭掉落,如下所示:
 connection.disconnection();
 下面经由过程一个具体的例子来熟悉下HttpURLConnection的用法。新建NetworkTest项目,起首修改activit_main.xml中的代码,如下所示:
 */
public class MainActivity extends Activity implements OnClickListener{

	public static final int SHOW_RESPONSE=0;
	private Button sendRequest=null;
	private TextView responseText=null;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			
			switch(msg.what){
			case SHOW_RESPONSE:
				String response=(String) msg.obj;
				//在这里进行UI操作,将结不雅显示到界面上
				responseText.setText(response);
				break;
			default:
				break;
			}
			
		}
		
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sendRequest=(Button) findViewById(R.id.send_request);
		responseText=(TextView) findViewById(R.id.response_text);
		sendRequest.setOnClickListener(this);
		
	}

	@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;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.d("MainActivity", "onClick(View v)!");
		if(v.getId()==R.id.send_request){
			sendRequestWithHttpURLConnection();
			
		}
		
	}
	
	
	private void sendRequestWithHttpURLConnection(){
		//开启线程来提议收集请求
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpURLConnection connection=null;
				
				try {
					URL url=new URL("http://www.baidu.com");
					connection =(HttpURLConnection) url.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中
					message.obj=response.toString();
					handler.sendMessage(message);
					
					
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					if(connection!=null){
						connection.disconnect();
					}
				}
			}
			
		}).start();
		
		
	}
	
	

}

DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
应用HttpClient
 调用一下openConnection()办法即可,如下所示:
     
<span style="font-size:18px;">    HttpClient是Apache供给的HTTP收集拜访接口,大年夜一开端的时刻就被惹人到android的api中。它可以
 完成和HttpURLConnection几乎一模一样的效不雅,但两者的之间的用法却竽暌剐较大年夜的差别,下面我们看看HttpClient的用法。
    起首我们要知道,HttpClient是一个接口,是以无法创建它的实例,平日情况下都邑创建一个DefaultHttpClient的实例,如下所示:
HttpClient httpClient=new DefaultHttpClient();
接下来如不雅想要提议一条GET请求,就可以创建一个HttpGet对象,并传入目标的收集地址,然后调用HttpClient的execute()办法即可:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);
如不雅是提议一条POST请求会比GET稍复杂一点,我们须要创建一个HttpPost对象,并传入目标收集地址,如下所示:
HttpPost httpPost=new HttpPost("http://www.baidu.com");
  然后经由过程一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后
  调用HttpPost的setEntity()办法将构建好的UrlEncodedFormEntity传入,如下所示:
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("username","jack"));
  params.add(new BasicNameValuePair("password","123456"));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
  httpPost.setEntity(entity);
  接下来的操作就和HttpGet一样了,调用HttpClient的execute()办法,并将HttpPost对象传入即可:
  httpClient.execute(httpPost);
  履行execute()办法之后会返回一个HttpResponse对象,办事器所返回的所有信息就会包含在这琅绫擎。平日情况下我们都邑先掏出办事器返回的状况
  码,如不雅等于200就解释要乞降响应都成功了,如下所示:
  if(httpResponse.getStatusCode()==200){
  
     //要乞降响应都成功了
  }
  接下来在这个if断定的内部掏出办事返回的具体内容,可声调用getEntity()办法获取到一个HttpEntity实例,然后再用
  EntityUtils.toString()这个静态办法将HttpEntity转化成字符串即可,如下所示:
  HttpEntity entity=httpResponse.getEntity();
  String response=EntityUtils.toString(entity);
  留意如不雅办事器返回的数据是带中文的,直接调用EntityUtils.toString()办法进行转换会有乱码的情况出现,这个时刻
  只须要在转换的时刻将字符集指定成utf-8就可以了,如下所示:
  String response=EntityUtils.toString(entity,"utf-8");</span>

 HttpClient是Apache供给的HTTP收集拜访接口,大年夜一开端的时刻就被惹人到android的api中。它可以
 完成和HttpURLConnection几乎一模一样的效不雅,但两者的之间的用法却竽暌剐较大年夜的差别,下面我们看看HttpClient的用法。
    起首我们要知道,HttpClient是一个接口,是以无法创建它的实例,平日情况下都邑创建一个DefaultHttpClient的实例,如下所示:
HttpClient httpClient=new DefaultHttpClient();
接下来如不雅想要提议一条GET请求,就可以创建一个HttpGet对象,并传入目标的收集地址,然后调用HttpClient的execute()办法即可:
HttpGet httpGet=new HttpGet("http://www.baidu.com");
httpClient.execute(httpGet);
如不雅是提议一条POST请求会比GET稍复杂一点,我们须要创建一个HttpPost对象,并传入目标收集地址,如下所示:
HttpPost httpPost=new HttpPost("http://www.baidu.com");
  然后经由过程一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后

  调用HttpPost的setEntity()办法将构建好的UrlEncodedFormEntity传入,如下所示:
  List<NameValuePair> params=new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("username","jack"));
  params.add(new BasicNameValuePair("password","123456"));
  UrlEncodedFormEntity entity=new UrlEncodedFormEntity(params,"utf-8");
  httpPost.setEntity(entity);
 get和post。get表示欲望大年夜办事器那边获取数据,而post则表示提交数据给办事器。写法如下:
  接下来的操作就和HttpGet一样了,调用HttpClient的execute()办法,并将HttpPost对象传入即可:
  httpClient.execute(httpPost);
  履行execute()办法之后会返回一个HttpResponse对象,办事器所返回的所有信息就会包含在这琅绫擎。平日情况下我们都邑先掏出办事器返回的状况
  
  }
  接下来在这个if断定的内部掏出办事返回的具体内容,可声调用getEntity()办法获取到一个HttpEntity实例,然后再用
  EntityUtils.toString()这个静态办法将HttpEntity转化成字符串即可,如下所示:
  HttpEntity entity=httpResponse.getEntity();
    以上就是HttpURLConnection的根本用法了,下面持续讲解别的一个办法。
  String response=EntityUtils.toString(entity);
  留意如不雅办事器返回的数据是带中文的,直接调用EntityUtils.toString()办法进行转换会有乱码的情况出现,这个时刻
  String response=EntityUtils.toString(entity,"utf-8");








  码,如不雅等于200就解释要乞降响应都成功了,如下所示:

接下来把NetworkTest这个项目改用HttpClient的方法再来实现一遍。
    构造部分完全不消修改,所以如今直接修改MainActivity中的代码,如下所示:
package com.jack.networktest;
import java.io.BufferedReader;
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.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity implements OnClickListener{

	public static final int SHOW_RESPONSE=0;
	private Button sendRequest=null;
	private TextView responseText=null;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case SHOW_RESPONSE:
				String response=(String) msg.obj;
				//在这里进行UI操作,将结不雅显示到界面上
				responseText.setText(response);
				break;
			default:
				break;
			}
			
		}
		
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		sendRequest=(Button) findViewById(R.id.send_request);
		responseText=(TextView) findViewById(R.id.response_text);
		sendRequest.setOnClickListener(this);
		
	}

	@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;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Log.d("MainActivity", "onClick(View v)!");
		if(v.getId()==R.id.send_request){
			//sendRequestWithHttpURLConnection();
			sendRequestWithHttpClient();
		}
		
	}
	
	
	private void sendRequestWithHttpURLConnection(){
		//开启线程来提议收集请求
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpURLConnection connection=null;
				
				try {
					URL url=new URL("http://www.baidu.com");
					connection =(HttpURLConnection) url.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中
					message.obj=response.toString();
					handler.sendMessage(message);
					
					
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}catch(Exception e){
					e.printStackTrace();
				}finally{
					if(connection!=null){
						connection.disconnect();
					}
				}
			}
			
		}).start();
		
		
	}
	
	
	private void sendRequestWithHttpClient(){
		new Thread(new Runnable(){

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try{
					HttpClient httpClient=new DefaultHttpClient() ;
					HttpGet httpGet=new HttpGet("http://www.baidu.com");
					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中
						message.obj=response.toString();
						handler.sendMessage(message);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
		}).start();
		
	}
	
	
	

}

膳绫擎的代码只是添加了一个sendRequestWithHttpClient()办法,并在send request按钮的点击事沂攀里去调用这个办法。在这个办法中同样照样先开启一个子线程,然后在子线程里应用HttpClient发出一条HTTP请求,请求的目标地址照样百度的首页。然后将办事器返回的数据存放到Message对象中,并用Handler将Message发送出去。
   如今从新运行法度榜样,点击send request按钮,你会发明和膳绫擎的结不雅一样,由此证实,应用HttpClient来发送Http请求的功能也已经实现了。
经由膳绫擎的演习,应当把HttpURLConnection 和  HttpClient的根本用法控制的差不多了。
http://blog.csdn.net/j903829182/article/details/42440155

相关案例查看更多