使用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具有解析数据的方法,解析返回数据可以更轻松。
注意:同样是网络操作,如果程序不是独自测试网络,不建议在主线程中进行网络操作,以上操作都是在单独线程中进行。