Android post请求网络数据(json作为参数)

参数说明:

//   path 请求路径

//   json  封装好的json数据,关于封装json数据的方法,最下面有。


public static String JsonPost(final String path, final JSONObject json) { 

BufferedReader in = null;
String result = "";
OutputStream os = null;
try {
URL url = new URL(path);
// 然后我们使用httpPost的方式把lientKey封装成Json数据的形式传递给服务器
// 在这里呢我们要封装的时这样的数据
// 我们把JSON数据转换成String类型使用输出流向服务器写
String content = String.valueOf(json);
// 现在呢我们已经封装好了数据,接着呢我们要把封装好的数据传递过去
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
// 设置允许输出
conn.setDoOutput(true);
conn.setRequestMethod("POST");
// 设置User-Agent: Fiddler
conn.setRequestProperty("ser-Agent", "Fiddler");
// 设置contentType
conn.setRequestProperty("Content-Type", "application/json");
os = conn.getOutputStream();
os.write(content.getBytes());
os.flush();
// 定义BufferedReader输入流来读取URL的响应
// Log.i("-----send", "end");

in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
if (conn.getResponseCode() == 200) {
while ((line = in.readLine()) != null) {
result += line;
}
}
} catch (SocketTimeoutException e) {
// Log.i("错误", "连接时间超时");
e.printStackTrace();
return "错误";
} catch (MalformedURLException e) {
// Log.i("错误", "jdkfa");
e.printStackTrace();
return "错误";
} catch (ProtocolException e) {
// Log.i("错误", "jdkfa");
e.printStackTrace();
return "错误";
} catch (IOException e) {
// Log.i("错误", "jdkfa");
e.printStackTrace();
return "错误";
}// 使用finally块来关闭输出流、输入流
finally {
try {
if (os != null) {
os.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;

}



json数据格式实例,需要的json数据在这里封装,如果格式中有jsonarray,直接加上去就行,最后将该方法返回的json数据直接作为参数放在上述网络请求的方法里

public JSONObject get jsonData() {

     JSONObject js=new JSONObject();

     try {

    js.put("name", "Sandy");

    js.put("age", "23");

    js.put("sex","男");

   } catch (JSONException e) {

   // TODO Auto-generated catch block

   e.printStackTrace();

  }

   return js;

}





  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值