Last time we talked about the network programming using URLConnection, URLConnection has been able to easily exchange information with the specified site, and there is a sub-class URLConnection under it: HttpURLConnection.
HttpURLConnection has been improved on the basis of urlconnection, adding some convenient methods for manipulating HTTP resources.
setRequestMethod(String):设置发送请求的方法 getResponseCode():获取服务器的响应代码getResponseMessage():获取服务器的响应消息
A) The code for the GET request:
conn=(HttpURLConnection)url.openConnection();//注意要大写conn.setRequestMethod("GET");conn.setConnectTimeout(8000);//连接超时的毫秒数conn.setReadTimeout(8000);//读取超时的毫秒数
b) The Code of the POST request
conn=(HttpURLConnection)url.openConnection();//注意要大写conn.setRequestMethod("POST");
c) Close the connection
if(conn!=null)conn.disconnect();
Note the required permissions:
Steps to use URLConnection:
① populate URLs as a URL object
URL url = new URL(String spec);
② Gets the client connection object to the server and is not connected at this time
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
③ Initialization of Connection objects
conn.setRequestMethod("GET"); //设置请求方式,注意大写conn.setConnectTimeout(5000);//设置连接超时时间conn.setReadTimeout(5000);//设置读取超时时间
④ send a request to establish a connection
conn.connect();
⑤ getting the stream in the server response
InputStream is = conn.getInputStream();
⑥ data in a stream (such as a string, picture)
Here's an example of downloading a picture using httpurlconnection (only with a little bit of skill, the first time to load the network image, the secondary image cache, and then load directly from the cache, without access to the network):
Effect:
Activity_main.xml
<?xml version= "1.0" encoding= "Utf-8"?><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 " tools:context = " Com.briup.httpurlconnection.MainActivity "; <buttonandroid:onclick="OnClick"android:layout_width="Match_ Parent "android:layout_height=" Wrap_content "android:text=" load picture "/> <ImageViewandroid:id= "@+id/iv" android:layout_width=" Wrap_content "android:layout_height=" wrap_content "/> </linearlayout>
Mainactivity.java
PackageCom.example.httpurlconnection;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.net.HttpURLConnection;ImportJava.net.MalformedURLException;ImportJava.net.URL;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.graphics.BitmapFactory;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.ImageView;ImportAndroid.widget.Toast; Public class mainactivity extends Activity { PrivateImageView IV;//Address of the network picture PrivateString Path ="Https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"; Public Static Final intSUCCESS =0x1;//Flag successfully loaded Public Static Final intFAIL =0x0;//Failed to load flags PrivateHandler Mhandler =NewHandler () {@Override Public void Handlemessage(Message msg) {Switch(msg.what) { CaseSUCCESS:iv.setImageBitmap ((Bitmap) msg.obj); Break; CaseFAIL:Toast.makeText (mainactivity. This,"Request Failed", Toast.length_long). Show (); Break;default: Break; } } };@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); IV = (ImageView) Findviewbyid (R.ID.IV); } Public void OnClick(View view) {FinalFile Mfile =NewFile (Getcachedir (),"A2.jpg");//Determine if there is a cache if(Mfile.exists ()) {//have cacheToast.maketext ( This,"Use Cache", Toast.length_long). Show (); Bitmap Bitmap = Bitmapfactory.decodefile (Mfile.getabsolutepath ()); Iv.setimagebitmap (bitmap); }Else{//No cache, request network NewThread () {@Override Public void Run() {Try{Toast.maketext (mainactivity). This,"No Cache", Toast.length_long). Show ();//1. Populating URLs as a URL objectURL url =NewURL (path);//2. Get the client-server connection object, which is not connected at this timeHttpURLConnection conn = (httpurlconnection) url.openconnection ();//3. Initializing the Connection objectConn.setrequestmethod ("GET");//Set request method, pay attention to uppercaseConn.setconnecttimeout ( the);//Set connection time-outConn.setreadtimeout ( the);//Set read timeout time //4. Sending a request, establishing a connectionConn.connect ();//Return code of 200 indicates successful request if(Conn.getresponsecode () = = $) {//Get the stream in the server responseInputStream is = Conn.getinputstream ();//Writes data from the server's stream to a local file, caches it.FileOutputStream fos =NewFileOutputStream (Mfile);byte[] B =New byte[1024x768];intLen =0; while(len = Is.read (b))! =-1) {Fos.write (b,0, Len); } fos.flush (); Fos.close ();//There is no data in the stream at this time //Get the picture from the fileBitmap Bitmap = Bitmapfactory.decodefile (Mfile.getabsolutepath ()); Message msg = Message.obtain ();//Load succeededMsg.what = SUCCESS; Msg.obj = bitmap; Mhandler.sendmessage (msg); }Else{Message msg = Message.obtain ();//Load failedMsg.what = FAIL; Mhandler.sendmessage (msg); } }Catch(Malformedurlexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }}}.start (); } }}
HttpURLConnection Source: http://download.csdn.net
--httpclient
android5.0之前.常用 android5.0之后,被HttpURLConnecetion替代 android6.0完全被舍弃 HttpClient是Apache提供的Http网络访问接口。完成的功能和HttpURLConnection几乎一模一样的效果,但两者的用法有很大的差别。 在一般情况下,如果只是需要向Web站点的某个简单页面提交请求并获取服务器响应,完全可以使用前面介绍的HttpURLConnection来完成,但是在绝大部分情况下,Web站点网页没这么简单,这些页面并不是通过一个简单的URL就可访问的,可能需要用户登录而且具有相应的权限才可访问该页面,在这种情况下,就需要涉及Session,Cookie的处理了。 HttpClient是一个简单的HTTP客户端,并不是浏览器。可以用于发送HTTP请求,接受HTTP响应,但不会缓存服务器的响应,不能执行HTML页面中嵌入的javascript代码,也不会对页面进行任何解析,处理。 HttpClient会自动维护与服务器之间的Session状态,但是前提是使用同一个HttpClient对象发送请求。
Steps to use HttpClient: HttpClient is an interface.
a)创建HttpClient对象:new DefaultHttpClient(); b)如果需要发送GET请求,创建HttpGet对象,并指定地址。 如果需要发送Post请求,创建HttpPost对象, c)如果需要发送请求参数,可调用HttpGet,HttpPost共同的setParams(HttpParams)方法来添加请求参数,对于HttpPost对象而言,也可调用setEntity(HttpEntity)方法设置请求参数。 使用HttpEntity下的UrlEncodedFormEntitiy对象传入一个放入BasicNameValuePair的集合中提交的数据。 如:HttpPost post=new HttpPost("");List<NameValuePair> list=new ArrayList<>();list.add(new BasicNameValuePair("name",name));list.add(new BasicNameValuePair("pwd", pwd));post.setEntity(new UrlEncodedFormEntity(list,"UTF-8")); d)调用HttpClient对象execute(HttpUriRequest)发送请求,执行该方法返回一个HttpResponse; e)调用HttpResponse的getstatusLine().getStatesCode()方法可以获取响应的状态码,如果是200就代码是成功的状态。调用HttpResponse的getEntity()方法获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。然后再用EntityUtils.toString(HttpEntity,"编码方式")将其转成为字符串。
--httpclient return different data parsing methods
A) return the normal text data
b) return HTML data
c) Return XML data
xml的解析可以采用sax,dom,dom4j,pull
d) return JSON data (mentioned in the last article JSON parsing)
Attention:
1. Chinese garbled problem: three kinds of ways
String N=urlencoder.encode ("Zhang San", "UTF-8");
String n=encodingutils.getstring ("Zhang San". GetBytes (), "UTF-8"); this way is obsolete.
Con.setrequestproperty ("Charset", "UTF-8");
The 2.HttpClient class will be able to use the compiled version below 6.0.
I deleted httpclient at 6.0,
In 5.1 He was out of date, and the official deprecated it.
Web programming for Android Development notes-network programming using HTTP