Este artículo describe la operación de encapsulación de la clase de herramientas HTTP de Java. Compártelo para su referencia, como sigue:
Implementación de la clase HTTP Tool: (a través del paquete Apache) la primera clase
import java.io.ioException; import org.apache.http.httpentity; import org.apache.http.httpesponse; import org.apache.http.httpstatus; importación.http.client.clientprotocolexception; import.apache.http.client.client; org.apache.http.client.methods.httpget; import org.apache.http.util.entityutils; import com.gooagoo.stcu.utils.http.httpclientutils; clase pública httprequest {private string errorMessage; // información/ *** HTTPS String Source** @param URL* URL Dirección* @return String Source**/ public String httpRequestString (String url) {string dultin = null; intente {httpentity httpentity = httprequest (url); if (httpentity! = null) {resultado = entityUtil.ToString (httpentity, "ursf-8"); // use UTF-8}} Catch (ioException e) {errorMessage = e.getMessage (); } resultado de retorno; } / *** HTTP FUNT FUENTE** @Param URL* URL DIRECCIÓN* @return Font Fuente** / public Byte [] httpRequestByTearray (String url) {byte [] result = null; intente {httpentity httpentity = httprequest (url); if (httpentity! = null) {result = entityUtilss.tobytearray (httpentity); }} Catch (ioException e) {errorMessage = e.getMessage (); } resultado de retorno; } / ** * Use el método http get para encontrar * * @param url * url dirección * @return httpentery icon * * / private httpentity httprequest (string url) {httpentity dutur = null; intente {httpget httpget = new httpget (url); Httpclient httpclient = httpclientutil.gethttpclient (); Httpresponse httpresponse; httpResponse = httpclient.execute (httpget); int httpStatUscode = httpResponse.getStatUsline (). getStatUscode (); / * * Determine si http es 200 */ if (httpstatuscode == httpstatus.sc_ok) {result = httpesponse.getEntity (); } else {errorMessage = "http:" + httpstatuscode; }} Catch (ClientProtocolException e) {errorMessage = e.getMessage (); } catch (ioException e) {errorMessage = e.getMessage (); } resultado de retorno; } / *** Mensaje de retorno** @return información** / public String getRormessage () {return this.errormessage; }}Implementación de la segunda clase:
paquete 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; import java.util.map.entry; import org.apache.http.httpponse; import org.apache.http.httpstatus; import org.apache.http.nameValuePair; import org.apache.http.client.httpclient; import org.apache.http.client.entity.urlaCodedformentity; org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; importar org.apache.http.message.basicnameValuePair; import opache.http.params.basichtpparams; org.apache.http.params.httpconnectionParams; importar org.apache.http.protocol.http; import org.apache.http.util.entityUtils; clase pública httpClientUtils {private statatal int request_timeOut = 5 * 1000; // SET SELIT TimeOut para 10 segundos. 1000; // Establecer el tiempo de espera de datos de espera durante 10 segundos // Parsexml estático parsexml = new Parsexml (); // Inicializar httpclient y establecer Tiempo de tiempo público estático httpclient gethttpClient () {BASICHTTPARAMS HTTPPARAMS = new BasichttPParams (); HttpconnectionParams.SetConnectionTimeOut (httparams, request_timeout); HttpconnectionParams.setSotimeOut (httparams, so_timeout); HttpClient Client = new DeFaulThttpClient (httparams); devolver el cliente; } public static static boolean dopost (url de cadena) lanza la excepción {httpclient cliente = gethttpclient (); Httppost httppost = new httppost (url); Respuesta httpresponse; respuesta = Client.execute (httppost); if (httpstatus.sc_ok == Response.getStatUsline (). getStatUscode ()) {return true; } client.getConnectionManager (). Shutdown (); devolver falso; } / ** * Método de publicación para la interacción del valor de retorno con remoto * * @param hashmap * @param url * @return * / public static string gethttpxml (hashmap <string, string> hashmap, string url) {string resphingsemsg = ""; Httppost solicitud = nuevo httppost (url); Lista <NameValuePair> params = new ArrayList <NameValuePair> (); Iterator <map.entry <string, string >> iter = hashmap.entryset () .Iterator (); while (iter.hasnext ()) {Entry <String, String> Entry = iter.next (); params.add (new BasicNameValuePair (Entry.getKey (), Entry.getValue ())); } try {request.setEntity (new UrlencodedFormentity (params, http.utf_8)); HttpClient Client = httpClientUtils.gethttpClient (); HttpResponse respuesta = client.execute (solicitud); if (respuesta.getStatUsline (). getStatUscode () == 200) {ResponseMSG = EntityUtils.ToString (Response.GetEntity ()); }} Catch (desconocidoHostException e) {E.PrintStackTrace (); } catch (Exception e) {E.PrintStackTrace (); } return ResponseMSg; } / ** * Mape para String Parámetros de empalme * * @param hashmap * @return * / public static string mapToString (hashmap <string, string> hashmap) {String parameterstr = ""; Iterator <map.entry <string, string >> iter = hashmap.entryset () .Iterator (); while (iter.hasnext ()) {Entry <String, String> Entry = iter.next (); ParameterTr + = "&" + Entry.getKey () + "=" + Entry.getValue (); } if (paramestr.contains ("&")) {parameterTr = parameterstr.replaceFirst ("&", "?"); } return ParameterTr; }}Para obtener más información sobre el contenido relacionado con Java, consulte los temas de este sitio: "Resumen de las habilidades de programación de socket de Java", "Resumen de las habilidades de operación de archivos y directorio de Java", "Tutorial sobre estructura de datos de Java y algoritmo", "Resumen de las habilidades de nodo de operación DOM de Java" y "Resumen de las habilidades de operación de java" "
Espero que este artículo sea útil para la programación Java de todos.