您的位置:首页 > 理论基础 > 计算机网络

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

2017-03-27 22:44 225 查看
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";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: