networktest<CODE 2 chaper9>

學(xué)習(xí)目的:1.使用HTTP訪問(wèn)網(wǎng)絡(luò) 2.使用HttpURIConnection</h3>

1.使用HTTP訪問(wèn)網(wǎng)絡(luò)


工作原理:客戶(hù)端向服務(wù)器發(fā)出HTTP請(qǐng)求 服務(wù)器接收到請(qǐng)求返回?cái)?shù)據(jù) 客戶(hù)端解析處理

2.使用HttpURIConnection(本例獲取的是html代碼)

布局

<Button
        android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Send Request" />

    <ScrollView//滾動(dòng)查看界面顯示不了的內(nèi)容
        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類(lèi)

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

       }
   }
private void sendRequestWithHttpURLConnection() {
       // 開(kāi)啟線程來(lái)發(fā)起網(wǎng)絡(luò)請(qǐng)求
       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();
                   // 下面對(duì)獲取到的輸入流進(jìn)行讀取
                   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();
   }

添加權(quán)限


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

3.提交數(shù)據(jù)給服務(wù)器(如:提交用戶(hù)名和密碼)數(shù)據(jù)用&隔開(kāi)

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

4.使用Okhttp

添加依賴(lài)

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'//自動(dòng)下載兩個(gè)庫(kù)Okhttp庫(kù) Okio庫(kù)

}

用Okhttp重寫(xiě)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() {
                // 在這里進(jìn)行UI操作,將結(jié)果顯示到界面上
                responseText.setText(response);
            }
        });
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,544評(píng)論 19 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,954評(píng)論 25 709
  • 1.OkHttp源碼解析(一):OKHttp初階2 OkHttp源碼解析(二):OkHttp連接的"前戲"——HT...
    隔壁老李頭閱讀 21,567評(píng)論 24 176
  • 〔她是恐懼的反義詞〕 逃離現(xiàn)實(shí)、拒絕平庸、原始嫉妒、神秘感,這四方面構(gòu)成了魅力。 一、逃離現(xiàn)實(shí)的欲望...
    飄風(fēng)雨閱讀 621評(píng)論 0 1
  • 忘記有多久沒(méi)有更文了,有些時(shí)候就寫(xiě)幾句話就敷衍了事。 今天一個(gè)朋友問(wèn)我多久沒(méi)有更新文章了,是不是忘記它的存在了,我...
    安心shine閱讀 302評(píng)論 0 2

友情鏈接更多精彩內(nèi)容