欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android中HttpURLConnection類使用介紹

 更新時(shí)間:2022年12月13日 15:52:39   作者:小鹿迷鹿  
早些時(shí)候其實(shí)我們都習(xí)慣性使用HttpClient,但是后來(lái)Android6.0之后不再支持HttpClient,需要添加Apache的jar才行,所以,就有很多開(kāi)發(fā)者放棄使用HttpClient了,HttpURLConnection畢竟是標(biāo)準(zhǔn)Java接口(java.net) ,適配性還是很強(qiáng)的

Http協(xié)議的認(rèn)識(shí):

Android中發(fā)送http網(wǎng)絡(luò)請(qǐng)求是很常見(jiàn)的,要有GET請(qǐng)求和POST請(qǐng)求。一個(gè)完整的http請(qǐng)求需要經(jīng)歷兩個(gè)過(guò)程:客戶端發(fā)送請(qǐng)求到服務(wù)器,然后服務(wù)器將結(jié)果返回給客戶端。

GET表示希望從服務(wù)器那里獲取數(shù)據(jù),而POST則表示希望提交數(shù)據(jù)給服務(wù)器。

通過(guò)Http訪問(wèn)網(wǎng)絡(luò)的三個(gè)步驟:

1、發(fā)送http請(qǐng)求

2、接受服務(wù)響應(yīng)

3、解析返回?cái)?shù)據(jù)

HttpURLConnection類位于java.net包中,它用于發(fā)送HTTP請(qǐng)求和獲取HTTP響應(yīng)。

話不多說(shuō),直接上代碼:

首先創(chuàng)建一個(gè)安卓項(xiàng)目。在xml中編寫如下代碼:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="獲取"
        />
    <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>

ScrollView是可供用戶滾動(dòng)的層次結(jié)構(gòu)布局容器,允許顯示比實(shí)際多的內(nèi)容,借助ScrollView控件,我們就可以以滾動(dòng)的形式查看屏幕外的那部分內(nèi)容。

上面的代碼主要是實(shí)現(xiàn),當(dāng)點(diǎn)擊按鈕時(shí),下面的滾動(dòng)視圖將展示其內(nèi)容。

在java中編寫如下代碼:

public class MainActivity extends AppCompatActivity {
   TextView response;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.button);
        response=(TextView)findViewById(R.id.response);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url=new URL("http://www.baidu.com");
                            HttpURLConnection connection=(HttpURLConnection)url.openConnection();
                            connection.setRequestMethod("GET");
                          InputStream inputStream=connection.getInputStream();
                          BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
                          StringBuilder stringBuilder=new StringBuilder();
                          String Line;
                          while ((Line=reader.readLine())!=null){
                              stringBuilder.append(Line);
                          }
                          show(stringBuilder);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }
    private void show(final StringBuilder stringBuilder) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                response.setText(stringBuilder);
            }
        });
    }
}

首先需要獲取到HttpURLConnection的實(shí)例,一般只需new出一個(gè)URL對(duì)象,并傳入目標(biāo)的網(wǎng)絡(luò)地址,然后調(diào)用一下openConnection()方法即可,如下所示:

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

在得到了HttpURLConnection的實(shí)例后,我們可以設(shè)置一下HTTP請(qǐng)求所使用的方法。常用的方法主要有兩個(gè):GET和POST。GET表示希望從服務(wù)器那里獲取數(shù)據(jù),而POST則表示希望提交數(shù)據(jù)給服務(wù)器。寫法如下:

connection.setRequestMethod(“GET”);

之后在調(diào)用getInputStream()方法就可以獲取到服務(wù)器返回的輸入流了,剩下的任務(wù)就是對(duì)輸入流進(jìn)行讀取。

最后別忘了在AndroidManifest.xml中聲明一下網(wǎng)絡(luò)權(quán)限和添加如下代碼(不加就會(huì)有錯(cuò)誤):

android:usesCleartextTraffic="true"

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.http4">
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

效果圖如下所示:

到此這篇關(guān)于Android中HttpURLConnection類使用介紹的文章就介紹到這了,更多相關(guān)Android HttpURLConnection內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論