HttpURLConnection和okHttp如何獲取網(wǎng)絡(luò)數(shù)據(jù)-創(chuàng)新互聯(lián)

這篇文章給大家分享的是有關(guān)HttpURLConnection和okHttp如何獲取網(wǎng)絡(luò)數(shù)據(jù)的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。

成都創(chuàng)新互聯(lián)長期為上千余家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為漳平企業(yè)提供專業(yè)的成都做網(wǎng)站、成都網(wǎng)站制作,漳平網(wǎng)站改版等技術(shù)服務(wù)。擁有10年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

代碼示例

xml如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_net"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 tools:context="com.example.waterlamp.NetActivity">
 <Button
  android:id="@+id/okhttp"
  android:text="okhttp請求"
  android:layout_width="150dp"
  android:layout_height="37dp"
  android:layout_alignBottom="@+id/http"
  android:layout_alignParentEnd="true"
  android:layout_alignParentTop="true" />

 <Button
  android:id="@+id/http"
  android:text="HTTP請求"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_alignParentTop="true"
  android:layout_alignParentStart="true" />

 <ScrollView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_alignParentStart="true"
 android:layout_below="@+id/okhttp"
 android:layout_alignParentBottom="true"
 android:layout_alignParentEnd="true" >
  <TextView
   android:id="@+id/stringData"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />
 </ScrollView>
</RelativeLayout>

activity如下:

public class NetActivity extends AppCompatActivity implements View.OnClickListener{
private Button http,okhttp;
 private TextView stringData;
 private String web="https://www.baidu.com";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_net);
  http= (Button) findViewById(R.id.http);
  okhttp= (Button) findViewById(R.id.okhttp);
  stringData= (TextView) findViewById(R.id.stringData);
  http.setOnClickListener(this);
  okhttp.setOnClickListener(this);
 }

 @Override
 public void onClick(View v) {
  switch (v.getId()){
   case R.id.http:
    sendRequestWithHttpURLConnection();
   break;
   case R.id.okhttp:
    sendRequestWithokHttp();
   break;
  }
 }
 private void sendRequestWithHttpURLConnection(){
  new Thread(new Runnable() {
   @Override
   public void run() {
    HttpURLConnection connection=null;
    BufferedReader reader=null;
    try {
     URL url=new URL(web);
     connection= (HttpURLConnection) url.openConnection();
     connection.setRequestMethod("GET");
     connection.setConnectTimeout(5000);
     connection.setReadTimeout(5000);
     InputStream in=connection.getInputStream();
     reader=new BufferedReader(new InputStreamReader(in));
     StringBuffer response=new StringBuffer();
     String line;
     while ((line=reader.readLine())!=null){
      response.append(line);
     }
     showRespond(response.toString());
    } catch (MalformedURLException e) {
     e.printStackTrace();
    } catch (IOException e) {
     e.printStackTrace();
    }finally {
     if (reader!=null){
      try {
       reader.close();
      } catch (IOException e) {
       e.printStackTrace();
      }
     }
    }
   }
  }).start();
 }

 private void showRespond(final String response) {
  runOnUiThread(new Runnable() {
   @Override
   public void run() {
    stringData.setText(response);
   }
  });
 }
 private void sendRequestWithokHttp(){
  new Thread(new Runnable() {
   @Override
   public void run() {

    try {
     OkHttpClient client=new OkHttpClient();
     Request request=new Request.Builder()
       .url(web).build();
     Response response=client.newCall(request).execute();
     String str=response.body().string();
     showRespond(str);
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }).start();
 }
}

注意:需要在加權(quán)限

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

2.okhttp3需要在gradle添加依賴

dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
  exclude group: 'com.android.support', module: 'support-annotations'
 })
 compile 'com.android.support:appcompat-v7:24.2.1'
 compile 'com.android.support:design:24.2.1'
 compile 'com.squareup.okhttp3:okhttp:3.4.1'//依賴
 testCompile 'junit:junit:4.12'
}

感謝各位的閱讀!關(guān)于“HttpURLConnection和okHttp如何獲取網(wǎng)絡(luò)數(shù)據(jù)”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

當(dāng)前題目:HttpURLConnection和okHttp如何獲取網(wǎng)絡(luò)數(shù)據(jù)-創(chuàng)新互聯(lián)
路徑分享:http://www.bm7419.com/article4/dcdsoe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站動態(tài)網(wǎng)站、網(wǎng)站制作、移動網(wǎng)站建設(shè)、微信小程序、網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)