刚开始学习安卓学到post json数据到服务器这里,经过搜集资料整理了一下方法,在此做下备份
方法:
/** * post请求 * * @param json 为Json字符串 * @param uri 为接口名 */ public static String postHTTP(String uri, String json) { HttpURLConnection httpURLConnection = null; String result = null; try { httpURLConnection = (HttpURLConnection) new URL(URL+uri).openConnection(); httpURLConnection.setRequestMethod("POST"); //Content-type字母区分大小写,特别注意 httpURLConnection.setRequestProperty("Content-type", "application/json"); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); httpURLConnection.connect(); //获取输出流对象,把请求参数发送打服务器接口 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(json.getBytes("utf-8")); outputStream.flush(); //获取服务器返回数据流 InputStream inputStream = httpURLConnection.getInputStream(); if (httpURLConnection.getResponseCode() == 200) { // 内存流对象 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } result = new String(byteArrayOutputStream.toByteArray(), "utf-8"); } else { //此处写入请求失败操作 } inputStream.close(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } return result; } l 调用:不能在UI线程里调用,需要子线程 try { JSONObject jsonObject = new JSONObject(); jsonObject.put("userName", "1111"); jsonObject.put("password", "1111"); String text = PostHttpURLConnection.postHTTP("login", jsonObject.toString()); if(text == null) return; JSONObject js = new JSONObject(text); ((EditText) findViewById(R.id.editText1)).setText(js.getString("m")); Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { e.printStackTrace(); }
需要写入网络权限:
<uses-permission android:name="android.permission.INTERNET"/>