zoukankan      html  css  js  c++  java
  • HTTP通信(HttpURLConnection)

    Android发送HTTP请求有两种,HttpURLConnection和HttpClient
    用法:
    1.获取HttpURLConnection实例
    new一个URL对象,传入一个网络地址;然后调用openConnection方法
     
    2.设置HTTP请求的方法
    常用的方法有两种:GET和POST方法,GET:从服务器获取数据;POST:发送数据给服务器
     
    3.设置一些东西
    比如设置连接超时,读取超时,服务器希望得到的消息头等
     
    4.getInputStream获取服务器返回的输入流
     
    5.对输入流进行读取
     
    6.disconnect关闭HTTP连接

    private void sendResquestWithURLConnection(){
    new Thread(new Runnable() {
    @Override
    public void run() {
    HttpURLConnection connection = null;
    try{
    URL url = new URL("http://www.baidu.com");
    connection = (HttpURLConnection) url.openConnection();

    connection.setRequestMethod("GET");

    connection.setConnectTimeout(8000);
    connection.setReadTimeout(8000);

    InputStream in = connection.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder response = new StringBuilder();
    String line;
    while((line = reader.readLine()) != null){
    response.append(line);
    }
    Message message = new Message();
    message.what = SHOW_RESPONSE;

    message.obj = response.toString();
    handler.sendMessage(message);
    }catch(Exception e){
    e.printStackTrace();
    }finally{
    if (connection != null){
    connection.disconnect();
    }
    }
    }
    }).start();

    private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    switch (msg.what){
    case SHOW_RESPONSE:
    String response = (String)msg.obj;
    responseText.setText(response);
    }

    }
    };

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

    @Override
    public void onClick(View v) {
    if (v.getId() == R.id.send_request){
    sendResquestWithURLConnection();
    }
    }
  • 相关阅读:
    Oracle startup startup nomount startup mount 的区别
    Linux 查看磁盘是否为SSD
    Spark入门实战系列--4.Spark运行架构
    Hbase 的java 增删改查操作
    Hbase 的一些重要网站链接,有空没空的搂两眼
    一段生成大数据测试数据的java code 片段
    一段简单的java 代码,用于日期格式转化
    一个简单的jsp 页面
    Scala 版 word count
    db2expln 查看执行plan
  • 原文地址:https://www.cnblogs.com/aisi-liu/p/5344279.html
Copyright © 2011-2022 走看看