1、MainActivity.java
package com.test.androidclient; import android.Manifest; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.test.androidclient.model.Student; import com.test.androidclient.util.NetTool; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private String URL= "http://192.168.13.26:8088"; private TextView tvData = null; private Button btnTxt = null; private Button btnGet = null; public NetTool nt; private Button btnUploadFile = null; private Button btnReadTxtFile = null; private Button btnDownloadFile = null; private static final int FILE_SELECT_CODE = 0; String filepath = ""; String filename = ""; String retStr = ""; final int REQUEST_WRITE=1;//申请权限的请求码 //需要将下面的IP改为服务器端IP private String txtUrl = URL + "/AppServer/SynTxtDataServlet.json"; private String url = URL + "/AppServer/SynDataServlet.json"; private String uploadUrl = URL + "/AppServer/UploadFileServlet.json"; private String fileUrl = URL + "/download/2.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvData = (TextView) findViewById(R.id.tvData); btnTxt = (Button) findViewById(R.id.btnTxt); btnGet = (Button) findViewById(R.id.btnGet); btnUploadFile = (Button) findViewById(R.id.btnUploadFile); btnDownloadFile = (Button) findViewById(R.id.btnDownloadFile); btnTxt.setOnClickListener(btnListener); btnGet.setOnClickListener(btnListener); btnUploadFile.setOnClickListener(btnListener); btnDownloadFile.setOnClickListener(btnListener); nt = new NetTool(this); /*try { run("http://192.168.1.3:8080/user/Test.json"); } catch (IOException e) { e.printStackTrace(); }*/ } View.OnClickListener btnListener = new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnTxt: Student student = new Student(); student.setLoginname("likun"); student.setPassword("123456"); student.setEmail("test@qq.com"); student.setMobile("13911111111"); student.setUsername("李坤"); student.setClasses("五期信息技术提高班"); Gson gson = new Gson(); String jsonTxt = gson.toJson(student); try { nt.sendTxt(txtUrl, jsonTxt,"UTF-8"); } catch (Exception e2) { e2.printStackTrace(); } break; case R.id.btnGet: Map<String, String> map = new HashMap<String, String>(); map.put("name", "李坤"); map.put("age", "26"); map.put("classes", "五期信息技术提高班"); try { retStr = NetTool.sendGetRequest(url, map, "utf-8"); } catch (Exception e) { e.printStackTrace(); } break; case R.id.btnUploadFile: // 需要在sdcard中放一张image.jsp的图片,本例才能正确运行 try { if (Build.VERSION.SDK_INT >= 23) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE); }else { retStr = NetTool.sendFile(uploadUrl, "/sdcard/Pictures/1.jpg", "1.jpg"); } } else { retStr = NetTool.sendFile(uploadUrl, "/sdcard/Pictures/1.jpg", "1.jpg"); } } catch (Exception e) { e.printStackTrace(); } break; case R.id.btnDownloadFile: if (Build.VERSION.SDK_INT >= 23) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE); }else { try { NetTool.downloadFile(fileUrl, "/sdcard/Pictures/", "newfile.jpg"); } catch (Exception e) { e.printStackTrace(); } } } else { try { NetTool.downloadFile(fileUrl, "/sdcard/Pictures/", "newfile.jpg"); } catch (Exception e) { e.printStackTrace(); } } break; default: break; } tvData.setText(retStr); } }; @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode==REQUEST_WRITE&&grantResults[0]== PackageManager.PERMISSION_GRANTED){ try { retStr = NetTool.sendFile(uploadUrl, "/sdcard/Pictures/1.jpg", "1.jpg"); } catch (Exception e) { e.printStackTrace(); } } } }
2、NetTool
1 package com.test.androidclient.util; 2 3 import android.os.Environment; 4 import android.os.Looper; 5 import android.util.Log; 6 import android.widget.Toast; 7 8 import com.test.androidclient.MainActivity; 9 10 import java.io.BufferedReader; 11 import java.io.File; 12 import java.io.FileOutputStream; 13 import java.io.IOException; 14 import java.io.InputStream; 15 import java.io.InputStreamReader; 16 import java.io.OutputStream; 17 import java.net.HttpURLConnection; 18 import java.net.URL; 19 import java.net.URLEncoder; 20 import java.util.Map; 21 import java.util.concurrent.TimeUnit; 22 23 import okhttp3.Call; 24 import okhttp3.Callback; 25 import okhttp3.MediaType; 26 import okhttp3.MultipartBody; 27 import okhttp3.OkHttpClient; 28 import okhttp3.Request; 29 import okhttp3.RequestBody; 30 import okhttp3.Response; 31 32 import static android.content.ContentValues.TAG; 33 34 /** 35 * NetTool:封装一个类搞定90%安卓客户端与服务器端交互 36 * 37 * 38 */ 39 public class NetTool { 40 private static final int TIMEOUT = 10000;// 10秒 41 private static OkHttpClient client = null; 42 public static final MediaType FORM_CONTENT_TYPE 43 = MediaType.parse("application/json; charset=utf-8"); 44 public static final MediaType MEDIA_OBJECT_STREAM 45 = MediaType.parse("application/octet-stream"); 46 47 public MainActivity aActivity = null; 48 public NetTool(MainActivity mainActivity) { 49 aActivity = mainActivity; 50 } 51 52 53 /** 54 * 传送文本,例如Json 55 */ 56 public void sendTxt(String urlPath, String txt, String encoding) 57 throws Exception { 58 RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, txt); 59 client = new OkHttpClient(); 60 Request request = new Request.Builder() 61 .url(urlPath) 62 .post(body) 63 .build(); 64 Call call = client.newCall(request); 65 call.enqueue(new Callback() { 66 // 2 67 @Override 68 public void onFailure(Call call, IOException e) { 69 //Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); 70 71 if (Looper.getMainLooper().getThread() == Thread.currentThread()) { 72 Log.d("eee", "Main Thread"); 73 74 } else { 75 Log.d("eee", "Not Main Thread11111"); 76 } 77 } 78 79 @Override 80 public void onResponse(Call call, final Response response) throws IOException { 81 // 3 82 if (Looper.getMainLooper().getThread() == Thread.currentThread()) { 83 Log.d("eee", "Main Thread"); 84 System.out.println(response.body().string()+"================================="); 85 } else { 86 System.out.println(response.body().string()+"=================================222222"); 87 Log.d("eee", "Not Main Thread22222"); 88 89 } 90 91 aActivity.runOnUiThread(new Runnable() { 92 @Override 93 public void run() { 94 Log.d(TAG, "code: "); 95 Toast.makeText(aActivity, String.valueOf(response.code()), Toast.LENGTH_SHORT).show(); 96 } 97 }); 98 } 99 }); 100 101 } 102 103 104 /** 105 * 上传文件 106 */ 107 public static String sendFile(String urlPath, String filePath, 108 String newName) throws Exception { 109 client = new OkHttpClient(); 110 //创建File 111 File file = new File(filePath); 112 //创建RequestBody 113 RequestBody body = RequestBody.create(MEDIA_OBJECT_STREAM, file); 114 RequestBody requestBody = new MultipartBody.Builder().addFormDataPart("filename", file.getName(), body).build(); 115 116 //创建Request 117 final Request request = new Request.Builder().url(urlPath).post(requestBody).build(); 118 final Call call = client.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); 119 call.enqueue(new Callback() { 120 @Override 121 public void onFailure(Call call, IOException e) { 122 Log.e(TAG, e.toString()); 123 } 124 125 @Override 126 public void onResponse(Call call, Response response) throws IOException { 127 if (response.isSuccessful()) { 128 String string = response.body().string(); 129 Log.e(TAG, "response ----->" + string); 130 } else { 131 } 132 } 133 }); 134 return null; 135 } 136 137 /** 138 * 通过get方式提交参数给服务器 139 */ 140 public static String sendGetRequest(String actionUrl, 141 Map<String, String> paramsMap, String encoding) throws Exception { 142 143 try { 144 StringBuilder tempParams = new StringBuilder(); 145 int pos = 0; 146 for (String key : paramsMap.keySet()) { 147 if (pos > 0) { 148 tempParams.append("&"); 149 } 150 tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); 151 pos++; 152 } 153 String params = tempParams.toString(); 154 RequestBody body = RequestBody.create(FORM_CONTENT_TYPE, params); 155 String requestUrl = String.format("%s?%s",actionUrl,tempParams.toString()); 156 client = new OkHttpClient(); 157 Request request = new Request.Builder() 158 .url(requestUrl) 159 160 .build(); 161 162 163 Call call = client.newCall(request); 164 call.enqueue(new Callback() { 165 @Override 166 public void onFailure(Call call, IOException e) { 167 Log.e(TAG, e.toString()); 168 } 169 170 @Override 171 public void onResponse(Call call, Response response) throws IOException { 172 if (response.isSuccessful()) { 173 String string = response.body().string(); 174 Log.e(TAG, "response ----->" + string); 175 } else { 176 } 177 } 178 }); 179 return "error"; 180 } catch (Exception e) { 181 Log.e(TAG, e.toString()); 182 } 183 return null; 184 185 } 186 187 /** 188 * 通过Post方式提交参数给服务器,也可以用来传送json 189 */ 190 public static String sendPostRequest(String urlPath, 191 Map<String, String> params, String encoding) throws Exception { 192 StringBuilder sb = new StringBuilder(); 193 // 如果参数不为空 194 if (params != null && !params.isEmpty()) { 195 for (Map.Entry<String, String> entry : params.entrySet()) { 196 // Post方式提交参数的话,不能省略内容类型与长度 197 sb.append(entry.getKey()).append('=').append( 198 URLEncoder.encode(entry.getValue(), encoding)).append( 199 '&'); 200 } 201 sb.deleteCharAt(sb.length() - 1); 202 } 203 // 得到实体的二进制数据 204 byte[] entitydata = sb.toString().getBytes(); 205 URL url = new URL(urlPath); 206 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 207 conn.setRequestMethod("POST"); 208 conn.setConnectTimeout(TIMEOUT); 209 // 如果通过post提交数据,必须设置允许对外输出数据 210 conn.setDoOutput(true); 211 // 这里只设置内容类型与内容长度的头字段 212 conn.setRequestProperty("Content-Type", 213 "application/x-www-form-urlencoded"); 214 // conn.setRequestProperty("Content-Type", "text/xml"); 215 conn.setRequestProperty("Charset", encoding); 216 conn.setRequestProperty("Content-Length", String 217 .valueOf(entitydata.length)); 218 OutputStream outStream = conn.getOutputStream(); 219 // 把实体数据写入是输出流 220 outStream.write(entitydata); 221 // 内存中的数据刷入 222 outStream.flush(); 223 outStream.close(); 224 // 如果请求响应码是200,则表示成功 225 if (conn.getResponseCode() == 200) { 226 // 获得服务器响应的数据 227 BufferedReader in = new BufferedReader(new InputStreamReader(conn 228 .getInputStream(), encoding)); 229 // 数据 230 String retData = null; 231 String responseData = ""; 232 while ((retData = in.readLine()) != null) { 233 responseData += retData; 234 } 235 in.close(); 236 return responseData; 237 } 238 return "sendText error!"; 239 } 240 241 242 243 244 245 /** 246 * 该函数返回整形 -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在 247 */ 248 public static int downloadFile(String urlStr, String path, String fileName) 249 throws Exception { 250 // 获取SD卡的目录 251 File sdCardDir = Environment.getExternalStorageDirectory(); 252 253 254 255 final File targetFile = new File(sdCardDir.getCanonicalPath() + "/Pictures/" + fileName); 256 client = new OkHttpClient(); 257 258 259 final Request request = new Request.Builder().url(urlStr).build(); 260 final Call call = client.newCall(request); 261 call.enqueue(new Callback() { 262 @Override 263 public void onFailure(Call call, IOException e) { 264 Log.e(TAG, e.toString()); 265 } 266 267 @Override 268 public void onResponse(Call call, Response response) throws IOException { 269 InputStream is = null; 270 byte[] buf = new byte[2048]; 271 int len = 0; 272 FileOutputStream fos = null; 273 try { 274 long total = response.body().contentLength(); 275 Log.e(TAG, "total------>" + total); 276 long current = 0; 277 is = response.body().byteStream(); 278 fos = new FileOutputStream(targetFile); 279 while ((len = is.read(buf)) != -1) { 280 current += len; 281 fos.write(buf, 0, len); 282 Log.e(TAG, "current------>" + current); 283 } 284 fos.flush(); 285 } catch (IOException e) { 286 Log.e(TAG, e.toString()); 287 } finally { 288 try { 289 if (is != null) { 290 is.close(); 291 } 292 if (fos != null) { 293 fos.close(); 294 } 295 } catch (IOException e) { 296 Log.e(TAG, e.toString()); 297 } 298 } 299 } 300 }); 301 return 0; 302 } 303 304 305 }