前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android OKHttp发送get网络请求实例

Android OKHttp发送get网络请求实例

作者头像
SingYi
发布2022-07-14 13:58:43
7450
发布2022-07-14 13:58:43
举报
文章被收录于专栏:Lan小站Lan小站

今天总算把安卓的网络请求弄了一下了。

image.png
image.png

获取的是我自己做的接口:https://api.565.ink/one/

随机一句英语,不得不说换一门语言,写法上真的有点不适应。

MainActivify.java

代码语言:javascript
复制
package ink.cik.firsthttpapp;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    TextView responseText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.btnSyncTest);
        responseText = findViewById(R.id.response_text);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("点击事件", "点击发送请求按钮");
                sendRequest();
            }
        });
    }

    private void sendRequest() {
        //开启线程发送请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://api.565.ink/one/").build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    showResponse(responseData);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void showResponse(final String response) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });

    }
}

AndroidMainifest.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="ink.cik.firsthttpapp">

    <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: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>

activity_main.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnSyncTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="同步测试" />

        <Button
            android:id="@+id/btnAsyncTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="异步测试" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:id="@+id/etId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="6"
            android:hint="输入用户编号"
            android:inputType="number" />

        <Button
            android:id="@+id/btnParamTest"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="doParamTest"
            android:text="传参测试" />

    </LinearLayout>

    <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="match_parent" />

    </ScrollView>
</LinearLayout>

build.gradle

代码语言:javascript
复制
apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"
    defaultConfig {
        applicationId "ink.cik.firsthttpapp"
        minSdkVersion 30
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.0'
    implementation 'com.squareup.okio:okio:2.8.0'
}

总结一下踩得一些坑。

坑一:

导入okhttp包导错了地方。

书上说,要在build.gradle中导入okhttp和okio

于是乎。。这两个里面果断的选择了第一个,因为名字是自己取的,按照python来说,默认的都是系统的。

image.png
image.png

结果出错了,其实是Module:app这个

坑二:本来我是本地搭建的环境,然后电脑端自己修改的hosts,将lan指向了127.0.0.1于是乎。

image.png
image.png

坑三:原本用的http,结果不行,百度发现得https

image.png
image.png
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档