Android的HTTP协议学习(一)

使用POST方法(一)

直接使用原版HTTP库:

1、添加必要包类:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

2、封装调用post方法:

    private void loginPost(final String usernames, final String passwords){
        final String loginURL = Contant.HttpsStyp + Contant.DomainNameOrIP + Contant.loginByUserName;

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(loginURL);

                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setUseCaches(false);
                    httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
                    httpURLConnection.setRequestProperty("Content-Type", "application/json");
                    httpURLConnection.connect();
                    DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
                    String content = "{" + "\"userName\": \""+usernames +"\",\"password\": \"" + passwords +"\"}";
                    outputStream.writeBytes(content);
                    outputStream.flush();
                    outputStream.close();

                    if(httpURLConnection.getResponseCode() == 200) {
                        InputStream is = httpURLConnection.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                        StringBuffer sb = new StringBuffer();
                        String readaline = "";
                        while((readaline = bufferedReader.readLine()) != null) {
                            sb.append(readaline);
                        }
                        is.close();
                        bufferedReader.close();
                        httpURLConnection.disconnect();
                        Log.d("test", sb.toString());
//                        Toast.makeText(this, ""+sb.toString(), Toast.LENGTH_SHORT).show();
                    } else {
                        Log.d("test", "visited failed!");
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

3、调用方法:

loginPost(username_Et.getText().toString(), password_Et.getText().toString());

使用POST方法(二)

利用okhttp库进行:

1、添加库类:

android {
......
allprojects {
    repositories {
        maven { url "https://jitpack.io" }
    }
}
......
}
dependencies {
......
implementation 'com.squareup.okhttp3:okhttp:4.2.2'
}

版本号这里是4.2.2,可以到https://github.com/square/okhttp进行查询。

2、调用方法:

private void loginPost(final String usernames, final String passwords) {

    final String loginURL = Contant.HttpsStyp + Contant.DomainNameOrIP + Contant.loginByUserName;
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    new Thread(new Runnable() {
        @Override
        public void run() {
            JSONObject json = new JSONObject();
            try {
                json.put("userName", usernames);
                json.put("password", passwords);
            } catch (JSONException e) {
                e.printStackTrace();
            }
                String post = json.toString();

                OkHttpClient client = new OkHttpClient();
                RequestBody body = RequestBody.create(JSON, post);
                Request request = new Request.Builder()
                        .url(loginURL)
                        .post(body)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
                        Log.d("test", "http fail!");
                    }

                    @Override
                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                        String string = response.body().string();
                        Log.d("test", "http success!"+string);
                        saveinformation();
                    }
                });
            }
    }).start();
}

仅仅是修改了线程中执行方式。okhttp具有解析数据的方法,解析返回数据可以更轻松。

注意:同样是网络操作,如果程序不是独自测试网络,不建议在主线程中进行网络操作,以上操作都是在单独线程中进行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值