Android安卓开发 HttpURLConnection使用教程笔记代码

package com.czh.httputil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import 

/**
 * Created by Administrator on 2016/1/15.
 */
public class HttpUtil {
    public static void sendHttpRequest
            (final String address, final HttpCallbackListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                   connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(
                            new InputStreamReader(in)
                    );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = bufferedReader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }
}




package com.czh.httputil;

/**
 * Created by Administrator on 2016/1/15.
 */
public interface HttpCallbackListener {
    public void onFinish(String s);
    public void onError(Exception e);
}

你可能感兴趣的:(Android安卓开发 HttpURLConnection使用教程笔记代码)