HTTP协议访问网络--HTTPURLConnection

HttpURLConnection

  • 调用openCollection()获得对象实例
  • 使用步骤
创建URL对象
调用openConnection调用HttpURLConnection对象
setRequestMethod设置HTTP请求使用方法:GET 或 POST
setConnectTimeout设置连接超时,setReadTimeout读取超时
调用getInputStream()方法获得服务器返回的输入流
输入流读取了InputStream in = conn.getInputStream();
调用disconnect()方法将HTTP连接关掉 
  • ScrollView
    以滚动形式查看屏幕外内容
public class MainActivity extends Activity {

    TextView responseText;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendRequest=(Button)findViewById(R.id.send_request);
        responseText=(TextView)findViewById(R.id.response_text);
        sendRequest.setOnClickListener((View.OnClickListener) this);
    }

    public void onClick(View v){
        if(v.getId()==R.id.send_request){
            sendRequestWithHttpURLConnection();
        }
    }

    public void sendRequestWithHttpURLConnection(){
    	//开启线程获得网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
            	
                HttpURLConnection connection=null;
                BufferedReader reader=null;
                try{
                    URL url=new URL("http://www.baidu.www");
                    connection=(HttpURLConnection)url.openConnection();
        
                    connection.setRequestMethod("GET");
                    
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
            
                    InputStream in=connection.getInputStream();
               
                    reader =new BufferedReader(new InputStreamReader(in));
                    StringBuilder response=new StringBuilder();
                    String line;
                    while((line=reader.readLine())!=null){
                    
                        response.append(line);
                    }
                    //将结果传入showResponse中
                    showResponse(response.toString());
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    if(reader!=null){
                        try{
                            reader.close();
                        }catch(Exception e){
                            e.printStackTrace();
                        }
                    }
                   
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
            	//在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }
}
  • 想要提交数据给服务器
connection.setRequestMethod("POST");
//获取输入流之前把数据写出来,每条数据以键值对形式存在,用&隔开
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("uersname==admin&password=123456");


public class PostUtils {
    public static String LOGIN_URL = "http://172.16.2.54:8080/HttpTest/ServletForPost";
    public static String LoginByPost(String number,String passwd)
    {
        String msg = "";
        try{
            HttpURLConnection conn = (HttpURLConnection) new URL(LOGIN_URL).openConnection();
            //设置请求方式,请求超时信息
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);
            //设置运行输入,输出:
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //Post方式不能缓存,需手动设置为false
            conn.setUseCaches(false);
            //我们请求的数据:
            String data = "passwd="+ URLEncoder.encode(passwd, "UTF-8")+
                    "&number="+ URLEncoder.encode(number, "UTF-8");
            //这里可以写一些请求头的东东...
            //获取输出流
            OutputStream out = conn.getOutputStream();
            out.write(data.getBytes());
            out.flush();
             if (conn.getResponseCode() == 200) {  
                    // 获取响应的输入流对象  
                    InputStream is = conn.getInputStream();  
                    // 创建字节输出流对象  
                    ByteArrayOutputStream message = new ByteArrayOutputStream();  
                    // 定义读取的长度  
                    int len = 0;  
                    // 定义缓冲区  
                    byte buffer[] = new byte[1024];  
                    // 按照缓冲区的大小,循环读取  
                    while ((len = is.read(buffer)) != -1) {  
                        // 根据读取的长度写入到os对象中  
                        message.write(buffer, 0, len);  
                    }  
                    // 释放资源  
                    is.close();  
                    message.close();  
                    // 返回字符串  
                    msg = new String(message.toByteArray());  
                    return msg;
             }
        }catch(Exception e){e.printStackTrace();}
        return msg;
    }
}
  • 设置权限
// AndroifManifest.xml
<uses-permissiom android:name="android.permission.INTERNET"/>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

blog....

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值