English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Asynchronous Callback Case of IP Query System

Without further ado, please see the code:

package com.lxj.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
public class Http extends Thread{
  // Callback interface for the end of download
  public interface IResult{
    void success(String msg);
    void fail(String msg);
  }
  // Create a reference to the network address
  String addr;
  // Create a reference to the callback interface
  IResult iResult ;
  // Generate a constructor to pass the network and interface references into it
  public Http(String addr, IResult iResult) {
    super();
    this.addr = addr;
    this.iResult = iResult;
    // Start the thread; once the thread is started, asynchronous operation is generated
    start();
  }
  @Override
  // Override the thread's run method, as multi-threading is required for any network operation
  public void run() {
    try {
      // Create a URL and pass the network address into it
      URL url = new URL(addr);
      try {
        // Use a character buffered reading stream to read network data
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
        // Create a StringBuffer object
        StringBuffer sb = new StringBuffer();
        // Create a temporary variable to store the string
        String temp;
        // Continue to read data as long as temp is not empty
        while ((temp = br.readLine()) != null) {
          sb.append(temp);
        }
        // After the data read is successful
        // Pass all the read data to the callback interface, and then transmit it through the interface
        iResult.success(sb.toString());
      catch (IOException e) {
        e.printStackTrace();
      }
    catch (MalformedURLException e) {
      e.printStackTrace();
      // Network request exception occurred
      iResult.fail("Network request failed");
    }
  }
}
package com.lxj.demo;
import net.sf.json.JSONObject;
import com.xykj.demo.Http.IResult;
public class IPRequest {
  // Callback interface for IP information request, it is necessary to use callback here because it is unknown when the HTTP download will be complete
  public interface IRequest{
    void success(IPBean ipBean);
    void fail(String msg);
  }
  // Just provide an IP address and a callback interface, and we can pass back the converted IP information object through the callback interface
  public void request(String IP, IRequest iRequest){
    // Append the user input IP address to the URL and initiate an HTTP request
    String addr ="http://apicloud.mob.com/ip/query?key=520520test&ip="
        + IP
        + "";
    new Http(addr, new IResult() {
      // The created IResult success and fail will not be called immediately, and must wait until the HTTP download is complete or an exception occurs
      @Override
      public void success(String msg) {
        // Convert the received JSON data into an IPBean object
        JSONObject jsonObject = JSONObject.fromObject(msg);
        IPBean ipBean = (IPBean) JSONObject.toBean(jsonObject, IPBean.class);
        // Generate a callback and pass the converted object to Demo
        iRequest.success(ipBean);
      }
      @Override
      public void fail(String msg) {
        // When the HTTP request fails
        iRequest.fail(msg);
      }
    });
  }
}
package com.lxj.demo;
public class IPBean {
  public static class Result{
    private String city;
    private String country;
    private String ip;
    private String province;
    public String getCity() {
      return city;
    }
    public void setCity(String city) {
      this.city = city;
    }
    public String getCountry() {
      return country;
    }
    public void setCountry(String country) {
      this.country = country;
    }
    public String getIp() {
      return ip;
    }
    public void setIp(String ip) {
      this.ip = ip;
    }
    public String getProvince() {
      return province;
    }
    public void setProvince(String province) {
      this.province = province;
    }
    @Override
    // Here, the toString method must be overridden, otherwise the memory address where the output is printed will be displayed
    public String toString() {
      return "city:" + city + "\ncountry:" + country + "\nip:"
          + ip + "\nprovince:" + province;
    }
  }
  Result result;
  private String msg;
  private String retCode;
  public Result getResult() {
    return result;
  }
  public void setResult(Result result) {
    this.result = result;
  }
  public String getMsg() {
    return msg;
  }
  public void setMsg(String msg) {
    this.msg = msg;
  }
  public String getRetCode() {
    return retCode;
  }
  public void setRetCode(String retCode) {
    this.retCode = retCode;
  }
}
package com.lxj.demo;
import java.util.Scanner;
import com.xykj.demo.IPRequest.IRequest;
public class Demo {
  public static void main(String[] args) {
    System.out.println("************Welcome to the IP Query System************");
    Scanner sc = new Scanner(System.in);
    // Create an IPRequest object
    IPRequest ipRequest = new IPRequest();
    while (true) {
      System.out.println("Please enter the IP to query:");
      String ip = sc.next();
      // Call the request method inside IPRequest
      ipRequest.request(ip, new IRequest() {
        @Override
        public void success(IPBean ipBean) {
          System.out.println("*************Query Results*************");
          System.out.println(ipBean.getResult());
        }
        @Override
        public void fail(String msg) {
          System.out.println(msg);
        }
      });
    }
  }
}

That's all for this article. I hope the content of this article can bring some help to everyone's learning or work, and I also hope to get more support for the Yelling Tutorial!

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like