post:
String url2 ="http://" + Constant.IP +":" + Constant.PORT +"" +
"/server/serviceUserLogistics";
ParamBean paramBean =new ParamBean(id, logisticsId, servicesUserCpId, smsCount);
OkHttpClient client2 =new OkHttpClient();
Gson gson =new Gson();
String json = gson.toJson(paramBean);
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = FormBody.create(mediaType, json);
Request request2 =new Request.Builder()
.url(url2)
.post(requestBody)
.build();
Call call = client2.newCall(request2);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// Toast.makeText(getActivity(),"internet error",Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response)throws IOException {
String result2 = response.body().string();
if (result2.equals("1")) {
System.out.println("successful");
Looper.prepare();
Toast.makeText(getActivity(),"successful", Toast.LENGTH_SHORT).show();
}else {
try {
//用JSON字符串来初始化一个JSON对象
JSONArray jsonArray =new JSONArray(result2);
if (jsonArray.length() ==0) {
System.out.println("error");
}else {
//然后读取result后面的数组([]号里的内容),用这个内容来初始化一个JSONArray对象
System.out.println("successful");
}
}catch (JSONException ex) {
Log.e("JSON Error: ", ex.toString());
}catch (Exception ignored) {
}
}
}
});
get
//Get请求
String param3 =usernameEditText.getText().toString();
ParamBean paramBean =new ParamBean();
//获取服务器data数据 为json形式
Gson gson =new Gson();
String url ="http://" + Constant.IP +":" + Constant.PORT +"/server/send/sms?phone=" + param3;
String json ="";
OkHttpClient client =new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = FormBody.create(mediaType, json);
Request request =new Request.Builder()
.url(url)
// .post(requestBody)
.build();
Call call2 = client.newCall(request);
call2.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(LoginActivity.this,"internet error", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response)throws IOException {
String result2 = response.body().string();
try {
//用JSON字符串来初始化一个JSON对象
JSONObject jsonObject =new JSONObject(result2);
//然后读取result后面的数组([]号里的内容),用这个内容来初始化一个JSONArray对象
String code = jsonObject.getString("randomNumeric");
APPData appData = (APPData) getApplicationContext();
appData.code = code;
// JSONArray aNews = new JSONArray(jsonObject.getString("data"));
// Log.i("the title: ", aNews.getJSONObject(0).getString("image"));
}catch (JSONException ex) {
Log.e("JSON Error: ", ex.toString());
}catch (Exception e) {
}
}
});