networktest<CODE 2 chaper9>

学习目的:1.使用HTTP访问网络 2.使用HttpURIConnection</h3>

1.使用HTTP访问网络


工作原理:客户端向服务器发出HTTP请求 服务器接收到请求返回数据 客户端解析处理

2.使用HttpURIConnection(本例获取的是html代码)

布局

<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_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

MainActivity类

@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;
               BufferedReader reader = 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();
                   // 下面对获取到的输入流进行读取
                   reader = new BufferedReader(new InputStreamReader(in));
                   StringBuilder response = new StringBuilder();
                   String line;
                   while ((line = reader.readLine()) != null) {
                       response.append(line);
                   }
                   showResponse(response.toString());
               } catch (Exception e) {
                   e.printStackTrace();
               } finally {
                   if (reader != null) {
                       try {
                           reader.close();
                       } catch (IOException e) {
                           e.printStackTrace();
                       }
                   }
                   if (connection != null) {
                       connection.disconnect();
                   }
               }
           }
       }).start();
   }

添加权限


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

3.提交数据给服务器(如:提交用户名和密码)数据用&隔开

connection.setRequestMethod("POST");
DataOutPutStream out=new DataOutPutStream(connection.getOutPutStream());
out.writeBytes("username=admin&password=123456789");

4.使用Okhttp

添加依赖

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.squareup.okhttp3:okhttp:3.4.1'//自动下载两个库Okhttp库 Okio库

}

用Okhttp重写http的例子

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

   private void sendRequestWithOkHttp() {
       new Thread(new Runnable() {
           @Override
           public void run() {
               try {
                   OkHttpClient client = new OkHttpClient();
                   Request request = new Request.Builder()

                           .url("http://www.baidu.com")
                           .build();
                   Response response = client.newCall(request).execute();
                   String responseData = response.body().string();

                  showResponse(responseData);
               } catch (Exception e) {
                   e.printStackTrace();
               }
           }
       }).start();
   }

   private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // 在这里进行UI操作,将结果显示到界面上
                responseText.setText(response);
            }
        });
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,544评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 178,954评论 25 709
  • 1.OkHttp源码解析(一):OKHttp初阶2 OkHttp源码解析(二):OkHttp连接的"前戏"——HT...
    隔壁老李头阅读 21,567评论 24 176
  • 〔她是恐惧的反义词〕 逃离现实、拒绝平庸、原始嫉妒、神秘感,这四方面构成了魅力。 一、逃离现实的欲望...
    飘风雨阅读 621评论 0 1
  • 忘记有多久没有更文了,有些时候就写几句话就敷衍了事。 今天一个朋友问我多久没有更新文章了,是不是忘记它的存在了,我...
    安心shine阅读 302评论 0 2

友情链接更多精彩内容