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

Android中HttpURLConnection類使用介紹

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

Http協(xié)議的認識:

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

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

通過Http訪問網(wǎng)絡的三個步驟:

1、發(fā)送http請求

2、接受服務響應

3、解析返回數(shù)據(jù)

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

話不多說,直接上代碼:

首先創(chuà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是可供用戶滾動的層次結(jié)構(gòu)布局容器,允許顯示比實際多的內(nèi)容,借助ScrollView控件,我們就可以以滾動的形式查看屏幕外的那部分內(nèi)容。

上面的代碼主要是實現(xiàn),當點擊按鈕時,下面的滾動視圖將展示其內(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的實例,一般只需new出一個URL對象,并傳入目標的網(wǎng)絡地址,然后調(diào)用一下openConnection()方法即可,如下所示:

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

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

connection.setRequestMethod(“GET”);

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

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

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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論