Cet article décrit l'opération d'encapsulation de Java implémentant la classe d'outils HTTP. Partagez-le pour votre référence, comme suit:
Implémentation de la classe d'outils HTTP: (via le package Apache) La première classe
Importer java.io.ioException; import org.apache.http.httpentity; import org.apache.http.httpResponse; import org.apache.http.httpstatu; import org.apache.http.client.httocoLException; import org.apache.http.client.httpclient; import org.apache.http.client.httpclient; import org.apache.http.client.httpclient; Import Org.apache.http.client.httpclient; Import Org.apache.http.Client.HTTPCLOCT; IMPORT ORG.APACH org.apache.http.client.methods.httpget; import org.apache.http.util.entityutils; import com.gooagoo.stcu.utils.http.httpclienttutils; public class httprequest {private string errorMessage; // Information / ** * Https String Source * * @param URL * URL Adresse * @return String Source * * / public String httpRequestString (string url) {string result = null; essayez {httpentity httpentity = httpRequest (url); if (httpentity! = null) {result = entityUtils.toString (httpentity, "urf-8"); // utilise utf-8}} catch (ioException e) {errorMessage = e.getMessage (); } Retour Résultat; } / ** * Http Font Source * * @param URL * URL Adresse * @return Font Source * * / public byte [] httpRequestByTearray (URL de chaîne) {byte [] result = null; essayez {httpentity httpentity = httpRequest (url); if (httpentity! = null) {result = entityUtils.toByTearray (httpentity); }} catch (ioException e) {errorMessage = e.getMessage (); } Retour Résultat; } / ** * Utilisez Http Get Method pour trouver * * @param URL * URL Adresse * @return httpentery icon * * / private httpentity httprequest (string url) {httpentity result = null; essayez {httpget httpget = new httpget (url); HttpClient httpClient = httpclientUtils.gethttpclient (); HttpResponse httpResponse; httpResponse = httpClient.Execute (httpget); int httpstaturuscode = httpResponse.getStatusline (). getStaturcode (); / * * Déterminez si Http est 200 * / if (httpStaturScode == httpstatus.sc_ok) {result = httpResponse.getEntity (); } else {errorMessage = "http:" + httpstaturuscode; }} catch (clientProtocolexception e) {errorMessage = e.getMessage (); } catch (ioException e) {errorMessage = e.getMessage (); } Retour Résultat; } / ** * Retour Message * * @return Information * * / public String getErrormaSage () {return this.errorMessage; }}Implémentation de la deuxième classe:
package com.demo.http; import java.net.unknownhostException; import java.util.arraylist; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.map; importer java.util.map.Entry; import org.apache.http.htt. org.apache.http.httpstatus; import org.apache.http.namevaluepair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlencodedFormentity; import org.apache.http.clit org.apache.http.impl.client.defaulthttpclient; import org.apache.http.message.basicNamevaluepair; import org.apache.http.params.httpconnectaMs; import org.apache.http.protocol.http; import org.apache.http.util.entityutils; classe publique httpclientUtils {private static final int requeand_timeout = 5 * 1000; // set request délaif de 10 seconds private static final int so_timeout = 10 * 1000; // Définir le délai d'attente des données pendant 10 secondes // parsexml statique ParsExml = new parsexml (); // Initialiser httpClient and Set Timeout public static httpclient gethttpclient () {Basichttpparams httpparams = new BasichTTPParams (); HttpConnectionParams.setConnectionTimeout (httpparams, request_timeout); HttpConnectionParams.SetSoTimeout (httpparams, so_timeout); HttpClient client = new DefaulthTTPClient (httpparams); RETOUR Client; } public static boolean doPost (string url) lève une exception {httpclient client = gethttpclient (); HTTPPOST HTTPPOST = NOUVEAU HTTPPOST (URL); Réponse HTTPResponse; réponse = client.Exécute (httppost); if (httpstatus.sc_ok == réponse.getStatusline (). getStaturcode ()) {return true; } client.getConnectionManager (). Shutdown (); retourne false; } / ** * POST Méthode pour l'interaction de valeur de retour avec la distance * * @param hashmap * @param url * @return * / public static String gethttpxml (hashmap <string, string> hashmap, string url) {String reventemsg = ""; Httppost request = new HTTPPOST (URL); List <nameValuepair> params = new ArrayList <NameValuepair> (); Iterator <map.entry <string, string >> iter = hashmap.entryset () .iterator (); while (iter.hasnext ()) {entrée <string, string> entry = iter.next (); params.add (new BasicNameValuePair (entry.getKey (), entry.getValue ())); } try {request.sentity (new UrLencomedFormentity (params, http.utf_8)); HttpClient client = httpclientUtils.gethttpclient (); HttpResponse Response = Client.Execute (demande); if (réponse.getStatusLine (). getStaturScode () == 200) {ResponseMsg = EntityUtils.ToString (Response.GetEntity ()); }} catch (UnknownHostException e) {e.printStackTrace (); } catch (exception e) {e.printStackTrace (); } return répondsg; } / ** * MAP TO String Paramètres d'épissage * * @param hashmap * @return * / public static String MaptoString (hashmap <string, string> hashmap) {String ParamètresTr = ""; Iterator <map.entry <string, string >> iter = hashmap.entryset () .iterator (); while (iter.hasnext ()) {entrée <string, string> entry = iter.next (); Parameterstr + = "&" + entry.getKey () + "=" + entry.getValue (); } if (paramestr.Contains ("&")) {Parameterstr = Parameterstr.replaceFirst ("&", "?"); } return ParamètresTr; }}Pour plus d'informations sur le contenu lié à Java, veuillez consulter les sujets de ce site: "Résumé des compétences de programmation Java Socket", "Résumé des compétences de fichier Java et d'opération de répertoire", "Tutorial sur la structure de données Java et l'algorithme", "Résumé de l'opération Java Dom Skills" et "Résumé des compétences en opération de cache Java"
J'espère que cet article sera utile à la programmation Java de tous.