复用Httpurlconnection


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * Created by Administrator on 2016/9/2.
 */
public class Httpurlconnection{

    public static String getid(final String urla) {
        try {
            URL url = new URL(urla);
            //URL链接对象,通过URL对象打开一个connection链接对像
            HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();

            //openConnection.setRequestProperty("Accept-Charset", "GBK");
            //openConnection.setRequestProperty("contentType", "GBK");
            openConnection.setConnectTimeout(5 * 1000);
            //openConnection.setRequestMethod("GET");

            openConnection.connect();
            int flag = openConnection.getResponseCode();
            if (flag == 200) {
                //调用urlConnection.getInputStream得到本次请求所返回的结果流
                InputStream inStream = openConnection.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

                String readerli;
                StringBuffer buffer = new StringBuffer();
                while ((readerli = in.readLine()) != null) {
                    buffer.append(readerli);
                }
                String str = buffer.toString();
                return str;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
  
 
  
 
  
//请求数据
new Thread(){
    @Override
    public void run() {
        super.run();
        String str= Httpurlconnection.getid(urla);
        Message message = new Message();
        message.what = 0;
        message.obj = str;
        handler.sendMessage(message);
    }
}.start();

你可能感兴趣的:(复用Httpurlconnection)