android studio java post请求数据,并转换为json对象
1、创建连接HttpURLConnection connect=(HttpURLConnection)url.openConnection();2、设置请求方式connect.setRequestMethod("POST");3、设置数据返回格式connect.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
·
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();
}
更多推荐
已为社区贡献1条内容
所有评论(0)