标准Java接口(java.net) ----HttpURLConnection,可以实现简单的基于URL请求、响应功能;
Get请求:
public String getconnbyget(String url){
StringBuilder result = new StringBuilder();
try {
//创建地址对象
URL u=new URL(url);
//创建HttpURLConnection链接对象
HttpURLConnection huconn=(HttpURLConnection) u.openConnection();
//连接服务器
huconn.connect();
// 取得输入流,并使用Reader读取,设定字符编码
BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
String line;
//读取返回值,直到为空
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
//关闭输入流
finally{
try{
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result.toString();
}
Post请求:
public String getconnbypost(String url,Map
headMap){
StringBuilder result = new StringBuilder();
try {
//创建地址对象
URL u=new URL(url);
//获取HttpURLConnection链接对象
HttpURLConnection huconn=(HttpURLConnection) u.openConnection();
// 发送POST请求必须设置如下两行,如果打算使用 URL 连接进行输出,则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false
huconn.setDoOutput(true);
//如果打算使用 URL 连接进行输入,则将 DoInput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 true
huconn.setDoInput(true);
//设置POST方式连接
huconn.setRequestMethod("POST");
//创建头信息map迭代器
Iterator
it = headMap.keySet().iterator();
//设置请求头配置信息
while (it.hasNext()) {
String key = it.next();
String value = headMap.get(key);
huconn.setRequestProperty(key, value);
}
//连接服务器
OutputStreamWriter out = new OutputStreamWriter(huconn.getOutputStream(),"UTF-8");
//写入请求体
out.write(data);
out.flush();
out.close();
// 取得输入流,并使用Reader读取,设定字符编码
BufferedReader in = new BufferedReader(new InputStreamReader(huconn.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
//关闭输入流
finally{
try{
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result.toString();
}
需要导入的jar包
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;