1.首先添加OkHttp依赖包
依赖包要根据自己的安卓版本选择,否则版本冲突会报错
2.在工具类HttpUtil中编写发送Get和Post请求方法
在发送请求的时候可能会出现NetworkOnMainThreadException异常,解决方法有两个
1.简单暴力,强制使用,代码修改简单
在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码
1 2 3 4
| if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); }
|
2.将请求网络资源的代码使用Thread去操作。在Runnable中做HTTP请求,不用阻塞UI线程。
1 2 3 4 5 6 7
| new Thread(new Runnable(){ @Override public void run() { cachedImage = asyncImageLoader.loadDrawable(imageUrl, position); imageView.setImageDrawable(cachedImage); } }).start();
|
编写发送Get请求方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
public static String sendGet(String url, Map<String, String> header) { String result = null; OkHttpClient okHttpClient = new OkHttpClient(); Request request = new Request.Builder() .url(url) .addHeader("Authorization", header.get("Authorization")) .build(); try { Response response = okHttpClient.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; }
|
编写发送Post请求方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
public static String sendPost(String url, Map<String, Object> params){ String result = null; OkHttpClient okHttpClient = new OkHttpClient(); FormBody.Builder builder = new FormBody.Builder(); for(Map.Entry<String, Object> param : params.entrySet()){ builder.add(param.getKey(), (String) param.getValue()); } FormBody requestBody = builder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); try { Response response = okHttpClient.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; }
|
3.在需要发送请求的地方调用方法
1 2 3 4 5 6 7 8 9 10 11
| String openDoor_url = ""; String authorization = ""; Map<String, String> header = new HashMap<>(); header.put("Authorization", authorization); HttpUtil.sendGet(openDoor_url, header);
String login_url = ""; Map<String, Object> params = new HashMap<>(); params.put("loginName", username); params.put("password", password); String str = HttpUtil.sendPost(login_url, params);
|
4.在记录一下获取JSON数组中的值
第一种方法:
1 2 3 4
| String str = "{'array':[{'id':5,'name':'张三'},{'id':6,'name':'李四'}]}"; JSONArray jsonArray = null; jsonArray = jsonobj.getJSONArray("array"); System.out.println(jsonArray.getJSONObject(0).get("name"));
|
1 2 3 4
| String str = "[{'columnId':5,'columnName':'人文历史'},{'columnId':2,'columnName':'商业视野'}]}"; JSONArray jsonArray = null; jsonArray = new JSONArray(str); System.out.println(jsonArray.getJSONObject(0).get("columnName"));
|
二、JAVA获取json中的全部键值对
1 2 3 4 5
| JSONObject json1=JSONObject.fromObject("{'username' : '11111','clientid' : '','password' : '222222'}"); Map<String, Object> map =json1; for (Entry<String, Object> entry : map.entrySet()) { System.out.println(entry.getKey()+"="+entry.getValue()); }
|