Android学习——HTTP请求

一、使用HttpURLConnection

    首先需要先获取HttpURLConnection的实例,一般只需new出一个URL对象,并传入目标的网络地址,然后调用一下openConnection()方法即可。如:

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

在得到HttpURLConnection的实例后,设置HTTP请求所使用的方法:GET和POST。

GET表示从服务器那里获取数据,之后调用getInputStreeam()方法就可以得到服务器返回的输入流了。如:

connection.setRequestMethod("GET");

而POST则表示提交数据给服务器,并在获取输入流之前把要提交的数据写出,每条数据都要一键值对的形式存在,数据与数据之间要用‘&’隔开。如:

    connection.setRequestMethod("POST");
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    out.writeBytes("username=admin&password=admin")

最后可以调用disconnect()方法将这个HTTP连接关闭掉。
注意: Android要求网络请求必须放在子线程中,且在子线程中无法进行UI操作。

其次,注意声明以下网络权限。修改AndroidManifest.xml中代码。如:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myApplication">
    <uses-permission android:name="android.permission.INTERNET"/>

    ...

</manifest>
二、使用OkHttp

    在使用OkHttp之前,需先在项目中添加OkHttp库的依赖。编辑app/build.gradle文件,在dependencies闭包中添加implementation 'com.squareup.okhttp3:okhttp:3.4.1' 如:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    implementation 'com.squareup.okhttp3:okhttp:3.4.1'
}

GET用法如下:

OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
                             .url(address)
                             .build();
Response response = client.newCall(request).execute();
String responseData =response.body().string();

POST用法如下:

Requestbody requestbody = new FormBody.Builder()
        .add("username","admin")
        .add("password","admin")
        .build();
Request request = new Request.Builder()
                             .url(address)
                             .post(requestbody)
                             .build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
String responseData =response.body().string();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值