http访问是java经常使用的。一般有三种请求方式。
- java原生的HttpURLConnection
- HTTPClient3(commons-httpclient) 第三方框架
- HTTPClient4.5(apache.httpclient)
HttpURLConnection传入参数用OutputStream(传参使用aa=bb样式),取返回值用InputStream,请求头setRequestProperty()
public static void doPost(String url){
HttpURLConnection connection = null;
String params = "param=zhangsan";
try {
URI uri = new URI(url);
connection = (HttpURLConnection)uri.toURL().openConnection();
//设置讲求时长
connection.setConnectTimeout(2000);
//设置读的时间
connection.setReadTimeout(1000);
//get请求传入GET
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
//设置是否将数据写入链接
connection.setDoOutput(true);
OutputStream outputStream = connection.getOutputStream();
outputStream.write(params.getBytes());
outputStream.flush();
outputStream.close();
//发起请求
connection.connect();
if(connection.getResponseCode() == 200){
InputStream inputStream = connection.getInputStream();
byte[] bytes = new byte[1024];
inputStream.read(bytes);
System.out.println(new String(bytes,"utf-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
httpClient3.1请求头使用setRequestHeader(),参数使用addParameter(),返回值还是使用InputStream
public static void doPost(String url, Map<String, String> params) {
//创建HttpClient实例
HttpClient httpClient = new HttpClient();
//设置httpClient连接主机服务器的超时时间
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
//创建Post请求方法实例
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//设置Post请求时长
post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 2000);
post.addParameter("param", "lisi");
try {
int statuCode = httpClient.executeMethod(post);
if (200 == statuCode) {
InputStream responseBodyAsStream = post.getResponseBodyAsStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(responseBodyAsStream));
String team = null;
while ((team = bufferedReader.readLine()) != null) {
System.out.println(team);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
httpClient4.5请求头使用setHeader(),传入参数使用setEntity(),返回参数又进行了封装直接使用httpResponse.getEntity()
public static void doPost(String url, Map<String, String> params) {
//通过默认配置创建个HttpClient实例
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse httpResponse = null;
//创建httpPost远程实例
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000)//连接主机服务超时时间
.setConnectionRequestTimeout(2000)//连接请求超时时间
.setSocketTimeout(2000)//读取数据超时时间
.build();
//为httpPost实例设置配置(get请求httpGet)
post.setConfig(requestConfig);
//设置请求头
post.setHeader("Content-Type", "application/json;charset=UTF-8");
//迭代请求参数map
List<NameValuePair> nvps = new ArrayList<>();
params.forEach((m, v) -> {
nvps.add(new BasicNameValuePair(m, v));
});
//为httpPost设置封装好的请求参数
try {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
//httpClient对象执行Post请求,并返回响应对象
httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
System.out.println(EntityUtils.toString(entity));
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != httpResponse) {
try {
httpResponse.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != client) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
在java中url和uri的区别?
uri:表示统一资源标识符引用
url:和般表示网络资源
url = uri.toUrl()