step1:
implementation 'com.squareup.okhttp3:okhttp:3.8.1'
implementation 'com.google.code.gson:gson:2.8.0'
step2:
<uses-permission android:name="android.permission.INTERNET" />
step3:
package com.example.mepositry;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private String mUrl2 = "http://192.168.0.231:8088/admin/login";
private Handler mHandler;
private OkHttpClient mOkHttpClient;
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
mHandler = new Handler();
mOkHttpClient = new OkHttpClient();
updateWeatherDataCoordinates();
}
public void updateWeatherDataCoordinates() {
UserSimple userSimple = new UserSimple("admin", "123456");
Gson gson = new Gson();
String userJson = gson.toJson(userSimple);
System.out.println("wrs:" + userJson);
RequestBody body = RequestBody.create(JSON, userJson);
Request request = new Request.Builder().url(mUrl2).post(body).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG", "onFailure");
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
final String stringJson = response.body().string();
Log.e("TAG", "onResponse" + stringJson);
}
});
}
}
step4:
package com.example.mepositry;
public class UserSimple {
private String username;
private String password;
public UserSimple(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
end
|