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";
本文介绍了如何使用Java进行HTTP请求的封装,包括POST和GET两种请求方式的具体实现。通过示例代码展示了如何设置请求头、处理请求体以及读取服务器响应等关键步骤。
3045

被折叠的 条评论
为什么被折叠?



