一般的来说发起网络请求和解析请求的内容都少不了OkHttp和Gson的帮助,它们极大的简化了我们的代码,还容易理解。
compile 'com.squareup.okhttp3:okhttp:3.8.0'
创建OkHttp的实例:
OkHttpClient client = new OkHttpClient();
创建一个Request的对象
如果想发起一条Http的请求需要创建一个Request的对象。
Request request = new Request.Builder().build();
通过设置url来获取有内容的实例。
例如:
Request request = new Request.Builder()
.url("网站地址")
.build();
之后调用OkhttpClient的newCall()方法来创建一个Call对象,并调用它的excute()方法来发送请求并获取服务器返回的数据,写法如下:
Response response = client.newCall(request).excute();
之后通过
response.body().string()来获取具体内容
POST请求:
RequestBody requestBody = new FormBody.Builder()
.add("username","admin")
.add("password","123456")
.build();
Request request = new Request.Builder()
.url("网站地址")
.post(requestBody)
.build();
之后和get方法一样使用excute()来发送请求和获取数据。
GSON:
compile 'com.google.code.gson:gson:2.7'
创建对象
Gson gson = new Gson();
非数组:
Person person = gson.fromJson(jsonData,Person.class);
数组:
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());
完整版:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static String TAG = "Main";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest = (Button)findViewById(R.id.send_request);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
send();
}
});
}
private void send(){
new Thread(new Runnable() {
@Override
public void run() {
try{
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("网站")
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().string();
parseJSONWithGSON(responseData);
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithGSON(String jsonData){
Gson gson = new Gson();
List<App>appList = gson.fromJson(jsonData,new TypeToken<List<App>>(){}.getType());
for (App app : appList){
System.out.println(app.getId());
Log.e(TAG, "parseJSONWithGSON: "+app.getId() );
Log.e(TAG, "parseJSONWithGSON: "+app.getName() );
Log.e(TAG, "parseJSONWithGSON: "+app.getVersion() );
}
}
}
App.java
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
进阶封装OkHttp3:
public class HttpUtil {
public static void sendOkHttpRequest(String address,okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);//enqueue自动开启子线程
}
}
之后可以这么写:
Button sendRequest = (Button)findViewById(R.id.send_request);
sendRequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HttpUtil.sendOkHttpRequest("http://www.firstproject.cn/get_data.json", new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//对异常情况进行处理
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseData = response.body().string();
parseJSONWithGSON(responseData);
}
});
}
});