常见的Android 网络请求的封装;

1:Post 请求时:

public static String getWebService_POST(String parames, String str) {
String json = “”;
Basic.msg = “”;
try {
URL url = new URL(str);
// 把JSON数据转换成String类型使用输出流向服务器写
String content = String.valueOf(parames);
Log.i(“mlog”, “参数:” + content);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”); // 修改
conn.setRequestProperty(“Content-Length”, String.valueOf(content.getBytes().length) + “”);
OutputStream os = conn.getOutputStream();
os.write(content.getBytes());
os.close();
// 服务器返回的响应码
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
json = readString(is);
Log.i(“mlog”, “json:” + json);
} else {
// Basic.msg=”服务器链接中断,请稍后再试”;
Log.i(“mlog”, “数据提交失败”);
}
} catch (Exception ex) {
// Basic.msg=”服务器链接中断,请稍后再试”;
Log.i(“mlog”, “Exception异常” + ex.getMessage());
}
return json;
}

public static byte[] readBytes(InputStream is) {
try {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

public static String readString(InputStream is) {
    return new String(readBytes(is));
}

2)get 请求的封装:

public String getWebService_GET(String s) {
String json = “”;
try {
URL url = new URL(s);
Log.i(“mlog”, “URL:” + s);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(“GET”);
conn.setRequestProperty(“Charset”, “UTF-8”);
conn.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded; charset=UTF-8”);
// 服务器返回的响应码
int code = conn.getResponseCode();
if (code == 200) {
InputStream is = conn.getInputStream();
json = readString(is);
Log.i(“mlog”, “json:” + json);
} else {
Log.i(“mlog”, “数据提交失败”);
}
} catch (Exception ex) {
Log.i(“mlog”, “Exception异常” + ex.getMessage());
}
return json;
}

例子:

public String GetHelpList() {
return getWebService_GET(Basic.GetHelpList_url);
}

public static String GetHelpList_url = basic_url + "UserCenter/GetHelpList";
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值