HTTP协议访问网络——HttpURLConnection
2015-09-12 20:25
232 查看
HttpURLConnection的使用
HttpURLConnection的实例
主函数
布局
总结
单线程下载和多线程下载及网络连接
MainActivity
IndexActivity
DownLoadActivity
MultiThread
activity_mainxml
activity_indexxml
activity_downloadxml
AndroidManifestxml的配置
URL url=new URL(“http://www.baidu.com“);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
2、得到了HttpURLConnection的实例之后,我们可以设置一下HTTP请求所使用的方法。常用的方法主要有两个,GET和POST。GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器,写法如下:
connection.setRequestMethod(“GET”);
3、现在我们可以进行一些自由的定制了,比如设置连接超时。读取超时的毫秒数,以及服务器希望得到的一些消息头等。示例如下:
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
4、调用getInputStream()方法就可以获取到服务器返回的输入流,剩下的就是对输入流进行读取,如下所示:
InputStream is=connection.getInputStream();
5、最后调用disconnect()方法将这个HTTP连接关闭掉。如下所示:
connection.disconnect();
2、在布局中我使用了一个新控件——ScrollView,由于手机屏幕空间一般较小,有时候过多的内容一屏是显示不下的,借助ScrollView控件的话就可以允许我们以滚动的形式查看屏幕以外的那部分内容。另外,布局中还设置了一个Button和一个TextView,Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。
总结:代码中用到了单线程和多线程,以及用来传递消息的Handler类、设置进度条的方法、RandomAccessFile类(是用来访问那些保存数据记录的文件的)和它的相关方法,比如: RandomAccessFile randomAccessFile=new RandomAccessFile(file,”rw”);
randomAccessFile.seek(start); 当然上面程序的很多方法我都已经给出了相应的解释,只要耐心看程序就会看懂滴
HttpURLConnection的实例
主函数
布局
总结
单线程下载和多线程下载及网络连接
MainActivity
IndexActivity
DownLoadActivity
MultiThread
activity_mainxml
activity_indexxml
activity_downloadxml
AndroidManifestxml的配置
HttpURLConnection的使用
1、首先要获取到HttpURLConnection的实例,一般只需要new出一个URL对象,并传入目标的网络地址,然后调用一下openConnection()方法即可。URL url=new URL(“http://www.baidu.com“);
HttpURLConnection connection=(HttpURLConnection)url.openConnection();
2、得到了HttpURLConnection的实例之后,我们可以设置一下HTTP请求所使用的方法。常用的方法主要有两个,GET和POST。GET表示希望从服务器那里获取数据,而POST则表示希望提交数据给服务器,写法如下:
connection.setRequestMethod(“GET”);
3、现在我们可以进行一些自由的定制了,比如设置连接超时。读取超时的毫秒数,以及服务器希望得到的一些消息头等。示例如下:
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
4、调用getInputStream()方法就可以获取到服务器返回的输入流,剩下的就是对输入流进行读取,如下所示:
InputStream is=connection.getInputStream();
5、最后调用disconnect()方法将这个HTTP连接关闭掉。如下所示:
connection.disconnect();
HttpURLConnection的实例
主函数
[code]public class MainActivity extends AppCompatActivity implements View.OnClickListener { public static final int SHOW_RESPPONSE=0X12; private Button mButtonSendRequest; private TextView mTextViewResponse; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what){ case SHOW_RESPPONSE: String content= (String) msg.obj; mTextViewResponse.setText(content); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButtonSendRequest= (Button) findViewById(R.id.send_request); mTextViewResponse= (TextView) findViewById(R.id.response); mButtonSendRequest.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.send_request: new Thread(new Runnable() { @Override public void run() { 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 is=connection.getInputStream(); //下面对获取到的输入流进行读取 BufferedReader br=new BufferedReader(new InputStreamReader(is)); StringBuilder builder=new StringBuilder();//这里用StringBuilder和StringBuffer都可以 String line=br.readLine(); while (line!=null) { builder.append(line); line = br.readLine(); } Message msg=handler.obtainMessage(); msg.what=SHOW_RESPPONSE; msg.obj=builder.toString(); handler.sendMessage(msg); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }).start(); break; } }
布局
[code]<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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity"> <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" android:layout_width="match_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>
总结
1、在按钮点击事件中先是开启了一个子线程,然后在子线程里使用了HttpURLConnection发出一条HTTP请求,请求的目的地址就是百度的首页,接着利用BufferedReader对服务器返回的流进行读取,并将结果存放到builder中。最后在放入Message对象中,至于这里为什么要使用Message对象——是因为子线程中无法对UI进行操作。我们希望可以将服务器返回的内容显示到界面上,所以创建了UI个Message对象并使用Handler将它发送出去,之后在handlerMessage()方法中对这条Message进行处理,最终取出结果并设置到TextView上。2、在布局中我使用了一个新控件——ScrollView,由于手机屏幕空间一般较小,有时候过多的内容一屏是显示不下的,借助ScrollView控件的话就可以允许我们以滚动的形式查看屏幕以外的那部分内容。另外,布局中还设置了一个Button和一个TextView,Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。
单线程下载和多线程下载、及网络连接
MainActivity
[code]public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button mButtonContent; private TextView mTextCiewContent; private static final int URL_CONNECT=0X123; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case URL_CONNECT: String content= (String) msg.obj; mTextCiewContent.setText(content); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mButtonContent= (Button) findViewById(R.id.button_content); mButtonContent.setOnClickListener(this); mTextCiewContent= (TextView) findViewById(R.id.textview_content); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button_content: new Thread(new Runnable() { @Override public void run() { ConnectURL(); } }).start(); break; } } private void ConnectURL() { try { // URL url=new URL("http://192.168.0.102:8080/MyServerTest/MyTestServerlet"); URL url=new URL("http://www.360.com"); URLConnection connection=url.openConnection(); InputStream is=connection.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); String line=br.readLine(); StringBuffer buffer=new StringBuffer(); while(line!=null){ Log.d("", line); buffer.append(line); line=br.readLine(); } Message msg=handler.obtainMessage(); msg.what=URL_CONNECT; msg.obj=buffer.toString().trim(); handler.sendMessage(msg); br.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
IndexActivity
[code]public class IndexActivity extends AppCompatActivity implements View.OnClickListener{ private Button mButtonURLConnection; private Button mButtonDownload; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_index); mButtonURLConnection= (Button) findViewById(R.id.button_urlconnection); mButtonDownload= (Button) findViewById(R.id.button_download); mButtonURLConnection.setOnClickListener(this); mButtonDownload.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.button_download: Intent intentDowanload=new Intent(getApplicationContext(),DownLoadActivity.class); startActivity(intentDowanload); break; case R.id.button_urlconnection: Intent intentUrl=new Intent(getApplicationContext(),MainActivity.class); startActivity(intentUrl); break; } } }
DownLoadActivity
[code]public class DownLoadActivity extends AppCompatActivity implements View.OnClickListener { private Button mButtonSingle; private Button mButtonMore; private ProgressBar mProgressBar; private int length; private static final int SEND_SUM = 0X123; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what){ case SEND_SUM: mProgressBar.setProgress(msg.arg1*100/length); break; } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); mButtonSingle = (Button) findViewById(R.id.button_single); mButtonMore = (Button) findViewById(R.id.button_more); mButtonSingle.setOnClickListener(this); mButtonMore.setOnClickListener(this); mProgressBar = (ProgressBar) findViewById(R.id.progressbar); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button_single: SingleDownloadTask singleDownloadTask = new SingleDownloadTask(); singleDownloadTask.execute(); break; case R.id.button_more: new Thread(new Runnable() { @Override public void run() { try { String urlPath = "http://192.168.0.43:8080/www/music/sj.mp3"; URL url = new URL(urlPath); URLConnection connection = url.openConnection(); length = connection.getContentLength(); File file = new File(Environment.getExternalStorageDirectory(), "aa.mp3"); if (!file.exists()) { file.createNewFile(); } MultiThread[] threads = new MultiThread[5]; for (int i = 0; i < 5; i++) { MultiThread thread = null; if (i == 4) { thread = new MultiThread(length / 5 * 4, length, urlPath, file.getAbsolutePath()); } else { thread = new MultiThread(length / 5 * i, length / 5 * ((i + 1)-1), urlPath, file.getAbsolutePath()); } thread.start(); threads[i] = thread; } boolean isFinish = true; while (isFinish) { int sum = 0; for (MultiThread thread : threads) { sum += thread.getSum(); } Message msg = handler.obtainMessage(); msg.what = SEND_SUM; msg.arg1 = sum; handler.sendMessage(msg); if (sum + 10 >= length) { isFinish = false; } Thread.sleep(1000); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); break; } } class SingleDownloadTask extends AsyncTask<String, Integer, String> { @Override protected void onProgressUpdate(Integer... values) {//...三个点表示参数个数不定 super.onProgressUpdate(values); mProgressBar.setProgress((int) (values[0] * 100.0 / values[1]));//sum表示数组[0],length表示数组[1] } @Override protected void onPostExecute(String s) { super.onPostExecute(s); } @Override protected String doInBackground(String... params) { try { URL url = new URL("http://192.168.0.43:8080/www/music/sj.mp3"); URLConnection connection = url.openConnection();//打开连接 length = connection.getContentLength();//得到内容总长度 InputStream is = connection.getInputStream();//得到输入流 //将Environment.getExternalStorageDirectory()路径下的takingmeaway.mp3文件实例化 File file = new File(Environment.getExternalStorageDirectory(), "takingmeaway.mp3"); if (!file.exists()) { file.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(file);//输出流将文件输入到file byte[] array = new byte[1024]; int sum = 0; int index = is.read(array);//从输入流中读出文件放在数组array中 while (index != -1) { outputStream.write(array, 0, index);//将数组中的文件写入到file中,从数组的第一个即下标号0处开始读入 sum += index; publishProgress(sum, length);//将参数传入onProgressUpdate中,设置进度条 index = is.read(array); } outputStream.flush(); outputStream.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
MultiThread
[code]public class MultiThread extends Thread{ private int sum=0; private long start; private long end; private String urlPath; private String filePath; public MultiThread(long start,long end, String url, String filePath) { this.start=start; this.end=end; this.urlPath=url; this.filePath=filePath; } public int getSum(){ return sum; } @Override public void run() { try { URL url=new URL(urlPath); URLConnection connection=url.openConnection(); connection.setAllowUserInteraction(true);//允许用户进行交互 //setRequestProperty是告诉服务器 我的客户端的配置、需求.这里设置了从开始到结束的范围 connection.setRequestProperty("Range", "bytes=" + start + "-" + end); InputStream is=connection.getInputStream(); File file=new File(filePath); if (!file.exists()){ file.createNewFile(); } //RandomAccessFile是用来访问那些保存数据记录的文件的 RandomAccessFile randomAccessFile=new RandomAccessFile(file,"rw"); randomAccessFile.seek(start);//在文件里移动用seek()方法; byte []array=new byte[1024]; int index=is.read(array); sum=0; while (index!=-1){ randomAccessFile.write(array,0,index); sum+=index; index=is.read(array); } randomAccessFile.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
activity_main.xml
[code]<ScrollView 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" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <Button android:id="@+id/button_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="连接网络" /> <TextView android:id="@+id/textview_content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="内容"/> </LinearLayout> </ScrollView>
activity_index.xml
[code]<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button_urlconnection" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="HTTPurlconnectionn"/> <Button android:id="@+id/button_download" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下载文件"/> </LinearLayout> </ScrollView>
activity_download.xml
[code]<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <ProgressBar android:id="@+id/progressbar" android:layout_width="match_parent" android:layout_height="25dp" android:layout_marginTop="20dp" style="@style/Base.Widget.AppCompat.ProgressBar.Horizontal"/> <Button android:id="@+id/button_single" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="单线程下载"/> <Button android:id="@+id/button_more" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="多线程下载"/> </LinearLayout> </ScrollView>
AndroidManifest.xml的配置
[code]<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.administrator.myurlconnection" > <!--连接网络的权限--> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <!--可写入存储卡的权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <!--可读存储卡的权限 --> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="myurlconnection" android:theme="@style/AppTheme" > <activity android:name=".IndexActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity"></activity> <activity android:name=".DownLoadActivity"></activity> </application> </manifest>
总结:代码中用到了单线程和多线程,以及用来传递消息的Handler类、设置进度条的方法、RandomAccessFile类(是用来访问那些保存数据记录的文件的)和它的相关方法,比如: RandomAccessFile randomAccessFile=new RandomAccessFile(file,”rw”);
randomAccessFile.seek(start); 当然上面程序的很多方法我都已经给出了相应的解释,只要耐心看程序就会看懂滴
*-*
相关文章推荐
- socket模型处理多个客户端
- 跳转到网络设置界面,ConnectivityManager,WebView,ScrollView
- 网络流之标号法
- Android 网络连接——WebView
- Linux网络配置
- HTTPS那个东西(一)-HTTPS原理
- 网络连接——文件下载(单线程/多线程)
- TCP协议中的三次握手和四次挥手(图解)
- linux下出现ping:unknown host www.baidu.com问题时的解决办法——ubuntu下局域网络的配置
- 一定要减少用户从网络获取资源的成本
- Android 网络连接——ConnectivityManager网络管理器
- OkHttp的简单使用
- apache HttpClient 3.X使用手册
- TCP协议中的三次握手和四次挥手(图解)
- TCP的状态和三次握手
- IP首部校验和的计算
- nyoj 170 网络的可靠性
- U3D HTTP 最好用的插件BestHttp
- 【网络】(四)网络相关函数使用简介
- 如何判断当前网络状况