• Android 使用 HTTP 协议访问网络


      正在看《第一行代码》,记录一下使用 HTTP 协议访问网络的内容吧!

      在Android发送Http请求有两种方式,HttpURLConnection和HttpClient。

       1.使用HttpURLConnection

       首先要获取到HttpURLConnection的实例,只需要new出一个URL对象,并传入目标网络地址,然后调用一下openConnect()方法。  

    1 URL url = new URL("http://www.baidu.com"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    View Code

        得到HttpURLConnection实例之后,设置HTTP请求使用的方法(POST和GET),GET是希望从服务器得到数据,而POST就是希望发生数据到服务器了。

       

    connection.setRequestMethod("GET"); 
    View Code

          这里可以对connection做一些设置,读取超时毫秒数,连接超时等等。

     

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

        接着调用getInputStream()方法就可以获得服务器返回的输入流了,这时就可以对输入流进行读取。最后需要关闭connection。

    InputStream in = connection.getInputStream(); 
    connection.disconnect();
    View Code

        具体代码(来自书本) 

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical" >  
        <Button         android:id="@+id/send_request"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Send Request" />  
        <ScrollView         android:layout_width="match_parent"         android:layout_height="match_parent" >  
            <TextView             android:id="@+id/response"             android:layout_width="match_parent"             android:layout_height="wrap_content" />     </ScrollView>  
    </LinearLayout> 
    View Code
    public class MainActivity extends Activity implements OnClickListener {  
     public static final int SHOW_RESPONSE = 0;  
     private Button sendRequest;  
    第 10章 看看精彩的世界,使用网络技术 
     399 
     private TextView responseText;  
     private Handler handler = new Handler() {  
      public void handleMessage(Message msg) {    switch (msg.what) {    case SHOW_RESPONSE:     String response = (String) msg.obj;     // 在这里进行UI操作,将结果显示到界面上     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) {    sendRequestWithHttpURLConnection();   }  }  
     private void sendRequestWithHttpURLConnection() {   // 开启线程来发起网络请求   new Thread(new Runnable() {    @Override    public void run() {     HttpURLConnection connection = null;     try {      URL url = new URL("http://www.baidu.com");      connection = (HttpURLConnection) url.openConnection(); 
    第一行代码——Android 
     400 
         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中      message.obj = response.toString();      handler.sendMessage(message);     } catch (Exception e) {      e.printStackTrace();     } finally {      if (connection != null) {       connection.disconnect();      }     }    }   }).start();  }  
    } 
    View Code

         最后别忘了添加网络权限。

     <uses-permission android:name="android.permission.INTERNET" /> 

        另外如果想向服务器发送数据,只需要将 HTTP请求 的方法改成 POST,并在获取输入流之前把要提交的数据写出即可,注意每条数据都要以键 值对的形式存在,数据与数据之间用&符号隔开,比如说我们想要向服务器提交用户名和密 码,就可以这样写:
    connection.setRequestMethod("POST");

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    out.writeBytes("username=admin&password=123456");

      

  • 相关阅读:
    jq判断鼠标滚轴向上滚动还是向下滚动
    Directory 中user Var 如何添加到通道变量中?
    Centos 6.5 freeswitch 编译mod_shout
    golang esl api
    opensips redis配置记录
    luasocket 安装记录 (FS1.4)
    luasocket 安装记录 (FS1.6)
    Callcenter 模块解析
    OpenSIPS 1.11.1安装记录
    阿里服务器挂载数据盘
  • 原文地址:https://www.cnblogs.com/ljy-1471914707/p/5446789.html
Copyright © 2020-2023  润新知