public String executeHttpGet(String urlStr) {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
if (urlStr != null && urlStr.length() > 0) {
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return result;
}
public String executeHttpPost(String urlStr, String postStr) {
String result = null;
URL url = null;
HttpURLConnection connection = null;
InputStreamReader in = null;
if (urlStr != null && urlStr.length() > 0) {
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Charset", "utf-8");
DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
dop.writeBytes(postStr);
dop.flush();
dop.close();
in = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(in);
StringBuffer strBuffer = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
strBuffer.append(line);
}
result = strBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return result;
}Android中的HTTP请求(GET/POST)
HTTP请求处理方法
最新推荐文章于 2021-05-28 10:46:47 发布
本文介绍了一个简单的Java类,该类提供了执行HTTP GET和POST请求的方法。GET方法通过URL获取资源并返回结果字符串;POST方法则接受URL和POST数据,设置必要的HTTP头信息,发送POST数据并读取响应。
8514

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



