复用Httpurlconnection

本文介绍了一个使用Java的HttpURLConnection类实现GET请求的具体示例。该示例展示了如何设置HTTP连接参数,如超时时间,并从指定URL读取响应数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值