Java implements a sample encapsulation operation for the Http utility class

  • 2020-12-16 05:58:37
  • OfStack

This article gives an example of how Java implements the encapsulation of the Http utility class. To share for your reference, the details are as follows:

Implementation of the http utility class :(through the apache package) class 1


import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import com.gooagoo.stcu.utils.http.HttpClientUtils;
public class HTTPRequest {
  private String errorMessage; //  � � information 
  /**
   * HTTP Find the string and source 
   *
   * @param url
   *      URL address 
   * @return  String source? 
   * */
  public String httpRequestString(String url) {
    String result = null;
    try {
      HttpEntity httpEntity = httpRequest(url);
      if (httpEntity != null) {
        result = EntityUtils.toString(httpEntity, "urf-8"); //  use UTF-8 � � 
      }
    } catch (IOException e) {
      errorMessage = e.getMessage();
    }
    return result;
  }
  /**
   * HTTP Words are requested and sources are generated 
   *
   * @param url
   *      URL address 
   * @return  The word � � � � the source 
   * */
  public byte[] httpRequestByteArray(String url) {
    byte[] result = null;
    try {
      HttpEntity httpEntity = httpRequest(url);
      if (httpEntity != null) {
        result = EntityUtils.toByteArray(httpEntity);
      }
    } catch (IOException e) {
      errorMessage = e.getMessage();
    }
    return result;
  }
  /**
   *  use HTTP GET Way � o 
   *
   * @param url
   *      URL address 
   * @return HttpEntiry � like 
   * */
  private HttpEntity httpRequest(String url) {
    HttpEntity result = null;
    try {
      HttpGet httpGet = new HttpGet(url);
      HttpClient httpClient = HttpClientUtils.getHttpClient();
      HttpResponse httpResponse;
      httpResponse = httpClient.execute(httpGet);
      int httpStatusCode = httpResponse.getStatusLine().getStatusCode();
      /*
       *  Sentenced to � HTTP � � � � 200
       */
      if (httpStatusCode == HttpStatus.SC_OK) {
        result = httpResponse.getEntity();
      } else {
        errorMessage = "HTTP: " + httpStatusCode;
      }
    } catch (ClientProtocolException e) {
      errorMessage = e.getMessage();
    } catch (IOException e) {
      errorMessage = e.getMessage();
    }
    return result;
  }
  /**
   *  Returns the message 
   *
   * @return  � � information 
   * */
  public String getErrorMessage() {
    return this.errorMessage;
  }
}

Implementation of the second class:


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;
import java.util.Map.Entry;
import org.apache.http.HttpResponse;
import 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.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class HttpClientUtils {
  private static final int REQUEST_TIMEOUT = 5 * 1000;//  Set request timeout 10 seconds 
  private static final int SO_TIMEOUT = 10 * 1000; //  Sets the timeout for waiting data 10 seconds 
  // static ParseXml parseXML = new ParseXml();
  //  Initialize the HttpClient , and set the timeout 
  public static HttpClient getHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParams);
    return client;
  }
  public static boolean doPost(String url) throws Exception {
    HttpClient client = getHttpClient();
    HttpPost httppost = new HttpPost(url);
    HttpResponse response;
    response = client.execute(httppost);
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
      return true;
    }
    client.getConnectionManager().shutdown();
    return false;
  }
  /**
   *  The return value of the interaction with the remote post way 
   *
   * @param hashMap
   * @param url
   * @return
   */
  public static String getHttpXml(HashMap<String, String> hashMap, String url) {
    String responseMsg = "";
    HttpPost request = new HttpPost(url);
    List<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 response = client.execute(request);
      if (response.getStatusLine().getStatusCode() == 200) {
        responseMsg = EntityUtils.toString(response.getEntity());
      }
    } catch (UnknownHostException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return responseMsg;
  }
  /**
   * map Turn the string   Stitching parameters 
   *
   * @param hashMap
   * @return
   */
  public static String mapToString(HashMap<String, String> hashMap) {
    String parameStr = "";
    Iterator<Map.Entry<String, String>> iter = hashMap.entrySet()
        .iterator();
    while (iter.hasNext()) {
      Entry<String, String> entry = iter.next();
      parameStr += "&" + entry.getKey() + "=" + entry.getValue();
    }
    if (parameStr.contains("&")) {
      parameStr = parameStr.replaceFirst("&", "?");
    }
    return parameStr;
  }
}

For more information about java, please refer to Java Socket Programming Skills summary, Java File and Directory Operation Skills Summary, Java Data Structure and Algorithm Tutorial, Java Operation Of DOM Node Skills Summary and Java Cache Operation Skills Summary.

I hope this article has been helpful in java programming.


Related articles: