HttpURLConnection基本使用

用法

1.首先我们需要获取到一个HttpURLConnection实例,一般需要new出一个URL对象,并传入目标网络地址,通过调用openConnection()方法获得HttpURLConnection实例。

2.得到该实例后。我们需要设置一下http请求的的方法,这里我们主要研究get和post,默认是使用get方法。get一般用于从服务器获取数据,post一般用于向服务器提交数据,设置请求方法使用函数setRequestMethod(“POST”)进行设置。

3.此外可以进行一些请求的限制,比如连接超时的时间等,可以通过setConnectTimeout设置超时时间。

4.获取服务器返回的输入流,使用getInputStream方法获取。

5.读取内容并处理

6.关闭连接,通过调用disconnect方法关闭当前的连接。

使用过程中不要忘记添加权限

<uses-permission android:name="android.permission.INTERNET" />

GET

public String get(String urlPath) {
HttpURLConnection connection = null;
InputStream is = null;
try {
URL url = new URL(urlPath);
//获得URL对象
connection = (HttpURLConnection) url.openConnection();
//获得HttpURLConnection对象
connection.setRequestMethod("GET");
// 默认为GET
connection.setUseCaches(false);
//不使用缓存
connection.setConnectTimeout(10000);
//设置超时时间
connection.setReadTimeout(10000);
//设置读取超时时间
connection.setDoInput(true);
//设置是否从httpUrlConnection读入,默认情况下是true;
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//相应码是否为200
is = connection.getInputStream();
//获得输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//包装字节流为字符流
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
connection = null;
}
if (is != null) {
try {
is.close();
is = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}

POST

private String post(String urlPath, Map<String, String> params) {
if (params == null || params.size() == 0) {
return get(urlPath);
}
OutputStream os = null;
InputStream is = null;
HttpURLConnection connection = null;
StringBuffer body = getParamString(params);
byte[] data = body.toString().getBytes();
try {
URL url = new URL(urlPath);
//获得URL对象
connection = (HttpURLConnection) url.openConnection();
//获得HttpURLConnection对象
connection.setRequestMethod("POST");
// 设置请求方法为post
connection.setUseCaches(false);
//不使用缓存
connection.setConnectTimeout(10000);
//设置超时时间
connection.setReadTimeout(10000);
//设置读取超时时间
connection.setDoInput(true);
//设置是否从httpUrlConnection读入,默认情况下是true;
connection.setDoOutput(true);
//设置为true后才能写入参数
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", String.valueOf(data.length));
os = connection.getOutputStream();
os.write(data);
//写入参数
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//相应码是否为200
is = connection.getInputStream();
//获得输入流
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//包装字节流为字符流
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
connection = null;
}
}
return null;
}
private StringBuffer getParamString(Map<String, String> params) {
StringBuffer result = new StringBuffer();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> param = iterator.next();
String key = param.getKey();
String value = param.getValue();
result.append(key).append('=').append(value);
if (iterator.hasNext()) {
result.append('&');
}
}
return result;
}
 版权声明:本文为AIDE教程网原创文章,转载请附上原文出处链接和本声明
本文链接: https://www.aidemx.cn/4.html

梦雪

专注于AIDE教程分享

    留下你的评论

    *评论支持代码高亮<pre class="prettyprint linenums">代码</pre>

    相关推荐