HttpURLConnection和HttpClient使用
Posted xuqiang7
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HttpURLConnection和HttpClient使用相关的知识,希望对你有一定的参考价值。
HttpURLConnection
这是Java的标准类,继承自URLConnection,可用于向指定网站发送GET/POST请求。
方法描述
void setRequestMethod(String method)
设置请求的方法,注意参数必须全大写;
void setFollowRedirects(boolean set)
设置是否自动重定向,默认是true;
void setRequestProperty(String key, String value)
设置请求的header;
使用步骤
第一步 使用java.net.URL封装HTTP资源的url,并使用openConnection方法获得HttpURLConnection对象;
第二步 设置请求方法,setRequestMethod("POST");
第三步 设置输入输出和其它权限;
第四步 设置http请求头,setRequestProperty("Charset", ‘UTF-8");
第五步 输入和输出数据;对InputStream和OutputStream的读写操作。
第六步 关闭输入和输出流。
示例代码如下:
private void sendPost() {
HttpURLConnection connection = null;
BufferedWriter writer = null;
try {
URL url = new URL("http", "www.baidu.com", 80, "/");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(false);
connection.setDoInput(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
OutputStream os = connection.getOutputStream();
writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write("user=chen&pass=ya");
writer.flush();
connection.connect();
if (connection.getResponseCode() == 200) {
recv(connection.getInputStream());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
}
private void recv(@NonNull InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String content;
while ((content = reader.readLine()) != null) {
System.out.println("recv: " + content);
}
} catch (IOException e) {
e.printStackTrace(