1、创建连接

HttpURLConnection connect=(HttpURLConnection)url.openConnection();

2、设置请求方式

connect.setRequestMethod("POST"); 

3、设置数据返回格式

connect.setRequestProperty("Content-Type", "application/json;charset=UTF-8");

4、接收数据

InputStream input=connect.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));

5、转换数据为字符串类型

	StringBuffer sb = new StringBuffer();  //创建字符串对象
	while ((line = in.readLine()) != null) {
	    sb.append(line);
	}

6、字符串转json对象

JSONObject reinfo = new JSONObject(sb.toString());  //字符串转json对象

示例代码如下:

    /**
     * post数据请求
     */
    private void postData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //String params = "{\"user_phone\":" +user_phone +",\"user_password\":" + user_password+  "}";
                String params = "{\"mid\":\"1\",\"token\":\"DA38B0A236D9FDA7BC07\"}";
                try {
                    URL url=new URL("https://地址");
                    HttpURLConnection connect=(HttpURLConnection)url.openConnection();
                    connect.setDoInput(true);
                    connect.setDoOutput(true);
                    connect.setRequestMethod("POST");
                    connect.setUseCaches(false);
                    connect.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                    OutputStream outputStream = connect.getOutputStream();
                    outputStream.write(params.getBytes());
                    int response = connect.getResponseCode();
                    if (response== HttpURLConnection.HTTP_OK)
                    {
                        System.out.println(response);
                        InputStream input=connect.getInputStream();
                        BufferedReader in = new BufferedReader(new InputStreamReader(input));
                        String line = null;
                        StringBuffer sb = new StringBuffer();  //创建字符串对象
                        while ((line = in.readLine()) != null) {
                            sb.append(line);
                        }
                        JSONObject reinfo = new JSONObject(sb.toString());  //字符串转json对象
                        System.out.println(reinfo.get("info"));  //用get获取json对象的值
                        //Log.i("请求结果", reinfo.get("info").toString());
                    }
                    else {
                        System.out.println(response);
                    }
                } catch (Exception e) {
                    Log.e("e:", String.valueOf(e));
                }
            }
        }).start();
    }
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐