HTTP訪問API接口

一般服務端提從的API接口,都為字符串,客戶端訪問獲取后,將取轉換為Json對象,對于此類操作,本質是訪問HTTP,得到字符串形式的body。

示例代碼如下所示:

public class HttpHelper {

    public interface HttpRequestCallback{
        void onGetContent(String text);
    }

    public static void httpGet(final String url, final HttpRequestCallback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection=null;
                try{
                    URL urlObject = new URL(url);
                    connection = (HttpURLConnection)urlObject.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);

                    InputStream in = connection.getInputStream();
                    BufferedReader bufr = new BufferedReader(new InputStreamReader(in));

                    StringBuilder response = new StringBuilder();
                    String line = null;
                    while((line=bufr.readLine()) != null){
                        response.append(line);
                    }

                    if(callback != null){
                        callback.onGetContent(response.toString());
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }finally {
                    closeConnection(connection);
                }
            }
        }).start();
    }

    public static void closeConnection(HttpURLConnection closeable){
        if(closeable != null){
            try{
                closeable.disconnect();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
    }
}

所屬標簽

無標簽

25选5玩法中奖