Le JDK fournit une certaine prise en charge des demandes de protocole sans état (HTTP).
Créons d'abord une classe de demande (httprequester).
Cette classe résume le code pour Java pour implémenter des demandes simples, comme suit:
La copie de code est la suivante:
Importer java.io.bufferedReader;
Importer java.io.ioException;
import java.io.inputStream;
Importer java.io.inputStreamReader;
import java.net.httpurlconnection;
Importer java.net.url;
import java.nio.charse.Charset;
importation java.util.map;
Importer java.util.vector;
/ **
* Objet de demande HTTP
*
* @author yymmiinnggg
* /
classe publique httprequester {
String privé defaultConTenTencoding;
public httprequester () {
this.defaultContenCoDcoding = charSet.defaultCharset (). name ();
}
/ **
* Envoyez une demande de GET
*
* @param urlstring
* Adresse URL
* objet de réponse @return
* @throws ioexception
* /
public httprespons sendGet (string urlstring) lève ioException {
Renvoie ce.send (urlstring, "get", null, null);
}
/ **
* Envoyez une demande de GET
*
* @param urlstring
* Adresse URL
* @param params
* Ensemble de paramètres
* objet de réponse @return
* @throws ioexception
* /
public httprespons sendGet (string urlstring, map <string, string> params)
lance iOException {
return this.send (urlstring, "get", params, null);
}
/ **
* Envoyez une demande de GET
*
* @param urlstring
* Adresse URL
* @param params
* Ensemble de paramètres
* Propriétés @param
* Demandez les attributs
* objet de réponse @return
* @throws ioexception
* /
public httpResponsons sendGet (string urlstring, map <string, string> params,
Map <String, String> Properties) lance ioException {
return this.send (urlstring, "get", params, propriétés);
}
/ **
* Envoyer la demande de poste
*
* @param urlstring
* Adresse URL
* objet de réponse @return
* @throws ioexception
* /
public httprespons sendPost (string urlstring) lève ioException {
Renvoie ce.send (urlstring, "post", null, null);
}
/ **
* Envoyer la demande de poste
*
* @param urlstring
* Adresse URL
* @param params
* Ensemble de paramètres
* objet de réponse @return
* @throws ioexception
* /
public httprespons sendPost (String urlstring, map <string, string> params)
lance iOException {
return this.send (urlstring, "post", params, null);
}
/ **
* Envoyer la demande de poste
*
* @param urlstring
* Adresse URL
* @param params
* Ensemble de paramètres
* Propriétés @param
* Demandez les attributs
* objet de réponse @return
* @throws ioexception
* /
public httpResponsons sendPost (String urlString, map <string, string> params,
Map <String, String> Properties) lance ioException {
return this.send (urlstring, "post", params, propriétés);
}
/ **
* Envoyer une demande HTTP
*
* @param urlstring
* objet de réflexion @return
* @throws ioexception
* /
HttpRespons privé Send (chaîne URLString, méthode String,
MAP <String, String> Paramètres, Map <String, String> Propriétés)
lance iOException {
HttpurlConnection urlConnection = null;
if (method.equalsignorecase ("get") && paramètres! = null) {
StringBuffer param = new StringBuffer ();
int i = 0;
for (String Key: Paramètres.KeySet ()) {
si (i == 0)
param.append ("?");
autre
param.append ("&");
Param.APPEND (KEY) .APPEND ("="). APPEND (paramètres.get (clé));
i ++;
}
urlstring + = param;
}
Url url = nouvelle URL (URLString);
urlConnection = (httpurlConnection) url.openconnection ();
urlConnection.setRequestMethod (méthode);
urlConnection.SetDoOutput (true);
UrlConnection.SetDoInput (true);
urlConnection.seTUsecaches (false);
if (propriété! = null)
for (String key: properties.keyset ()) {
UrlConnection.AdDrequestProperty (Key, Properties.get (Key));
}
if (method.equalsignorecase ("post") && paramètres! = null) {
StringBuffer param = new StringBuffer ();
for (String Key: Paramètres.KeySet ()) {
param.append ("&");
Param.APPEND (KEY) .APPEND ("="). APPEND (paramètres.get (clé));
}
urlConnection.getOutputStream (). Write (param.toString (). GetBytes ());
urlConnection.getOutputStream (). Flush ();
urlConnection.getOutputStream (). Close ();
}
Renvoie ce.makeContent (urlstring, urlconnection);
}
/ **
* Obtenez l'objet de réponse
*
* @param urlconnection
* objet de réponse @return
* @throws ioexception
* /
Httprespons privé MakeContent (URLSTRING STRACE,
Httpurlconnection urlconnection) lève ioException {
HttpRespons httpResponser = new httpRespons ();
essayer {
InputStream dans = urlConnection.getInputStream ();
BufferedReader BufferedReader = new BufferedReader (
Nouveau InputStreamReader (IN));
httpResponser.ContentCollection = new Vector <string> ();
StringBuffer temp = new StringBuffer ();
String Line = BufferedReader.Readline ();
while (line! = null) {
httpResponser.ContentCollection.add (ligne);
Temp.APPEND (LINE) .APPEND ("/ R / N");
line = buttereDreader.readline ();
}
BufferedReader.Close ();
String ecod = urlConnection.getConTenCcoding ();
if (ecod == null)
eCOD = this.defaultContentencoding;
httpResponser.urlString = urlString;
httpResponser.defaultport = urlconnection.getUrl (). getDefaultport ();
httpResponser.file = urlconnection.getUrl (). getFile ();
httpResponser.host = urlconnection.getUrl (). gethost ();
httpResponser.path = urlconnection.getUrl (). getPath ();
httpResponser.port = urlconnection.getUrl (). getport ();
httpResponser.protoCol = urlconnection.getUrl (). getProtoCol ();
httpResponser.Query = urlConnection.getUrl (). getQuery ();
httpResponser.ref = urlconnection.getUrl (). getRef ();
httpResponser.UserInfo = urlconnection.getUrl (). getUserInfo ();
httpResponser.Content = new String (temp.ToString (). GetBytes (), ecod);
httpResponser.ContenCoding = eCOD;
httpResponser.code = urlconnection.getResponSECODE ();
httpResponser.Message = urlConnection.getResponseMessage ();
httpResponser.ContentType = urlConnection.getContentType ();
httpResponser.Method = urlConnection.getRequestMethod ();
httpResponser.connectTimeout = urlconnection.getConnectTimeout ();
httpResponser.readTimeout = urlConnection.getReadTimeout ();
retour httpResponser;
} catch (ioexception e) {
jeter e;
} enfin {
if (urlconnection! = null)
urlconnection.disconnect ();
}
}
/ **
* Le jeu de caractères de réponse par défaut
* /
String public getDefaultContenCoDcoding () {
Renvoyez ce.DefaultContenCoDcoding;
}
/ **
* Définissez le jeu de caractères de réponse par défaut
* /
public void setDefaultConTenTencoding (String defaultConTenCoding) {
this.defaultContenCoDcoding = defaultContenCoding;
}
}
Deuxièmement, jetons un coup d'œil à l'objet de réponse (httprespons). L'objet de réponse n'est en fait qu'un bean de données, qui résume les données de résultat de la réponse de la demande, comme suit:
La copie de code est la suivante:
Importer java.util.vector;
/ **
* Objet de réponse
* /
classe publique httprespons {
String URLString;
int defaultport;
File de chaîne;
String host;
Path de chaîne;
port int;
Protocole de chaîne;
Requête de chaîne;
String Ref;
String userInfo;
String ContentEncoding;
String Content;
String ContentType;
Int Code;
Message de chaîne;
Méthode de chaîne;
int connectTimeout;
int readTimeout;
Vector <string> contentCollection;
public String getContent () {
retourner le contenu;
}
String public getContentType () {
return contentType;
}
public int getcode () {
code de retour;
}
public String getMessage () {
retour du message;
}
Vector public <string> getContentCollection () {
return contentCollection;
}
String public getContenCoding () {
return ContentEncoding;
}
String public getMethod () {
Méthode de retour;
}
public int getConnectTimeout () {
return connectTimeout;
}
public int getReadTimeout () {
retourner readTimeout;
}
public String getUrlString () {
retour URLSTRING;
}
public int getdefaultport () {
return defaultport;
}
public String getFile () {
return fichier;
}
public String gethost () {
retour hôte;
}
public String getPath () {
chemin de retour;
}
public int getport () {
port de retour;
}
String public getProtoCol () {
protocole de retour;
}
public String getQuery () {
requête de retour;
}
String public getRef () {
RETOUR REF;
}
String public getUserInfo () {
return userInfo;
}
}
Enfin, écrivons une classe d'application pour tester si le code ci-dessus est correct
La copie de code est la suivante:
import com.yao.http.httprequester;
import com.yao.http.httprespons;
Test de classe publique {
public static void main (String [] args) {
essayer {
HttpRequester demande = new httpRequester ();
HttpRespons hr = request.sendGet ("// www.vevb.com");
System.out.println (hr.getUrlString ());
System.out.println (hr.getProtoCol ());
System.out.println (hr.Gethost ());
System.out.println (hr.getport ());
System.out.println (hr.getContenCoding ());
System.out.println (hr.getMethod ());
System.out.println (hr.getContent ());
} catch (exception e) {
e.printStackTrace ();
}
}
}