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

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

   1.使用HttpURLConnection

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

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

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

   

connection.setRequestMethod("GET"); 

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

 

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

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

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

    具体代码(来自书本) 

<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>
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(); }
}

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

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

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

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

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

  

最新文章

  1. java自带工具-jps、jinfo、jstack、jstat、jmap
  2. ESXi 5.5开启并配置SNMP
  3. CF #296 (Div. 1) A. Glass Carving 线段树
  4. Linux Apache prefork和worker的原理详解
  5. MySQLdb模块的安装
  6. Kd-Tree算法原理和开源实现代码
  7. redisTemplate keys方法 为空
  8. 安卓 handler解析
  9. SSH免密码(日志三)
  10. 【经验随笔】 Tomcat多个APP使用相同名称环境变量导致问题
  11. SQL Server(1)数据库基础
  12. 野路子码农系列(1) 创建Web API
  13. JPG、PNG、GIF、SVG 等格式图片区别
  14. 10本Java架构师必读书籍
  15. Python中的test测试
  16. mvn2gradle
  17. HDU 2298(纯物理加解一元二次方程)
  18. 深度学习FPGA实现基础知识10(Deep Learning(深度学习)卷积神经网络(Convolutional Neural Network,CNN))
  19. MFC中控件添加了变量后修改
  20. method invocation

热门文章

  1. HDU 5534 Partial Tree (完全背包变形)
  2. 删除对象中的key
  3. Spring REST实践之REST基本介绍
  4. 本地存储(cookie&amp;sessionStorage&amp;localStorage)
  5. JPA的主键生成策略
  6. 如何在KVM中管理存储池
  7. nginx 配置虚拟主机(支持php)
  8. Win7环境下VS2010配置Cocos2d-x-2.1.4最新版本号的开发环境
  9. NAT后面的FTP SERVER终极篇
  10. C++ Primer 学习笔记_46_STL实践与分析(20)--容器特有的算法