1: What is HTTP? Hypertext Transfer Protocol (Hypertext Transfer Protocol-HTTP) is a protocol designed to enable clients and servers to communicate smoothly. HTTP works with Request-response protocol (Request-reply protocol) between the client and the server. 2:http programming
1>: Use get to get a picture of the server side, put in local = = "Get the server things with Get way better
Packageget;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.net.HttpURLConnection;ImportJava.net.URL; Public classhttputil{/*** Get a picture of the server side using get method *@throwsIOException*/ Public StaticInputStream getInputStream (String path)throwsioexception {URL url=NewURL (path); HttpURLConnection Con=(HttpURLConnection) url.openconnection (); //Set Request ModeCon.setrequestmethod ("GET");//the default request method is get//Setting the connection time-out periodCon.setconnecttimeout (5000); //settings can read data from the server sideCon.setdoinput (true);//The default value is TrueInputStream in=NULL; //determine if the server-side response code is if(Con.getresponsecode () ==200) { in=Con.getinputstream (); } returnIn ; } Public Static voidMakeimg (InputStream in)throwsIOException {fileoutputstream fos=NewFileOutputStream ("File\\img.jpg"); byte[] B =New byte[1024]; intLen = 0; //read the image data returned by the server while(len = In.read (b))!=-1) {Fos.write (b,0, Len); } fos.close (); In.close (); }}Object-oriented code
Package get; Import java.io.IOException; Public class test{ publicstaticvoidthrows IOException { = "Http://localhost:9999/day16/img2.jpg"; Httputil.makeimg (Httputil.getinputstream (path));} }
Client
2: Use post to submit user name and password, and obtain server-side verification results = = "need to return data to use post, server-side code in the blog has
PackagePost;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.util.ArrayList;Importjava.util.List;ImportJava.util.Map;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.client.ClientProtocolException;Importorg.apache.http.client.HttpClient;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.message.BasicNameValuePair; Public classhttputil{ Public StaticString Sendbypost (String path,map<string,string> params,string encode)throwsclientprotocolexception, IOException {//first, each pair of child data to be submitted is encapsulated into the Namevaluepair type.list<namevaluepair> list =NewArraylist<namevaluepair>(); for(Map.entry<string, string>En:params.entrySet ()) {List.add (NewBasicnamevaluepair (En.getkey (), En.getvalue ())); } //organize the submitted data into a submitted formaturlencodedformentity entity =Newurlencodedformentity (list, encode); //Create a Submit method objectHttpPost post =Newhttppost (path); Post.setentity (entity); //create an object to execute the commitHttpClient client =Newdefaulthttpclient (); //Execute CommitHttpResponse response =Client.execute (POST); if(Response.getstatusline (). Getstatuscode () ==200) {InputStream in=response.getentity (). getcontent (); returnGetResult (In,encode); } return NULL; } Private StaticString GetResult (InputStream in, string encode)throwsIOException {bytearrayoutputstream BOS=NewBytearrayoutputstream (); byte[] arr =New byte[1024]; intLen = 0; while(len = In.read (arr))!=-1) {bos.write (arr),0, Len); } return NewString (Bos.tobytearray (), encode); }}Object-oriented code
PackagePost;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map; Public classtest{/** * @paramargs *@throwsIOException*/ Public Static voidMain (string[] args)throwsIOException {Map<String,String> params =NewHashmap<string, string>(); Params.put ("username", "Li Peng"); Params.put ("PWD", "123456"); String Path= "Http://localhost:9999/day16/servlet/LoginServlet"; String encode= "Utf-8"; System.out.println (httputils.sendbypost (path, params, encode)); }}Client
3: Submit the user name and password using the introduction method provided by the jar package in Apache and get the server-side validation results
PackageApache;ImportJava.io.ByteArrayOutputStream;Importjava.io.IOException;ImportJava.io.InputStream;Importjava.io.UnsupportedEncodingException;Importjava.util.ArrayList;ImportJava.util.HashMap;Importjava.util.List;ImportJava.util.Map;ImportOrg.apache.http.HttpResponse;ImportOrg.apache.http.NameValuePair;Importorg.apache.http.client.ClientProtocolException;Importorg.apache.http.client.HttpClient;Importorg.apache.http.client.entity.UrlEncodedFormEntity;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.message.BasicNameValuePair; Public classHttputil { Public StaticString Sendbypost (String path,hashmap<string,string> params,string encode)throwsclientprotocolexception, IOException {//first, each pair of child data to be submitted is encapsulated into the Namevaluepair type.list<namevaluepair> list =NewArraylist<namevaluepair>(); for(Map.entry<string, string>En:params.entrySet ()) {List.add (NewBasicnamevaluepair (En.getkey (), En.getvalue ())); } //organize the submitted data into a submitted formaturlencodedformentity entity =Newurlencodedformentity (list, encode); //Create a Submit method objectHttpPost post =Newhttppost (path); Post.setentity (entity); //create an object to execute the commitHttpClient client =Newdefaulthttpclient (); //Execute CommitHttpResponse response =Client.execute (POST); if(Response.getstatusline (). Getstatuscode () ==200) {InputStream in=response.getentity (). getcontent (); returnGetResult (In,encode); } return NULL; } Private StaticString GetResult (InputStream in, string encode)throwsIOException {bytearrayoutputstream BOS=NewBytearrayoutputstream (); byte[] arr =New byte[1024]; intLen = 0; while(len = In.read (arr))!=-1) {bos.write (arr),0, Len); } return NewString (Bos.tobytearray (), encode); }}Object-oriented code
PackageAppache;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map; Public classtest{/** * @paramargs *@throwsIOException*/ Public Static voidMain (string[] args)throwsIOException {Map<String,String> params =NewHashmap<string, string>(); Params.put ("username", "Li Peng"); Params.put ("PWD", "123456"); String Path= "Http://localhost:9999/day16/servlet/LoginServlet"; String encode= "Utf-8"; System.out.println (httputil.sendbypost (path, params, encode)); }}Client Code
Java HTTP Programming Summary