1.示例
- get请求,参数可以拼接在url上
- post请求,参数使用json字符串
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.10</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
package org.example;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.CharArrayBuffer;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class TTest {
public static String getHttp(String url) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL urls = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
out = new PrintWriter(conn.getOutputStream());
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
result = in.lines().collect(Collectors.joining());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
public static String getJson(String url) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet post = new HttpGet(url);
CloseableHttpResponse response = null;
try {
post.setHeader("Content-Type", "application/json");
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String postJson(String url, String jsonString) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
CloseableHttpResponse response = null;
try {
post.setHeader("Content-Type", "application/json");
if (null != jsonString) {
post.setEntity(new ByteArrayEntity(jsonString.getBytes(StandardCharsets.UTF_8)));
}
response = httpClient.execute(post);
if (response != null && response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entityToString(entity);
}
return result;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
if (response != null) {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String entityToString(HttpEntity entity) throws IOException {
String result = null;
if (entity != null) {
long length = entity.getContentLength();
if (length != -1 && length < 2048) {
result = EntityUtils.toString(entity, "UTF-8");
} else {
try (InputStreamReader reader1 = new InputStreamReader(entity.getContent(), StandardCharsets.UTF_8)) {
CharArrayBuffer buffer = new CharArrayBuffer(2048);
char[] tmp = new char[1024];
int l;
while ((l = reader1.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
result = buffer.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return result;
}
public static String postForm(String postURL,String name,String age){
PostMethod postMethod = new PostMethod(postURL) ;
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
NameValuePair[] data = {
new NameValuePair("name",name),
new NameValuePair("age",age)
};
postMethod.setRequestBody(data);
HttpClient httpClient = new HttpClient();
String result = null;
try {
httpClient.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) {
System.out.println(getHttp("https://www.baidu.com"));
System.out.println("--------------------------------华丽的分割线-----------------------------------");
System.out.println(postJson("https://www.baidu.com", null));
System.out.println("--------------------------------华丽的分割线-----------------------------------");
System.out.println(postForm("https://www.baidu.com", null, null));
}
}
2.打印
<!DOCTYPE html><!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=
--------------------------------华丽的分割线-----------------------------------
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=
</script> <a href=
--------------------------------华丽的分割线-----------------------------------
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<style data-for="result" id="css_result">
body{color:#333;background:#fff;padding:6px 0 0;margin:0;position:relative;min-width:900px}body,th,td,.p1,.p2{font-family:arial}p,form,ol,ul,li,dl,dt,dd,h3{margin:0;padding:0;list-style:none}input{padding-top:0;padding-bottom:0;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}table,img{border:0}td{font-size:9pt;line-height:18px}
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.*;
public class TTest {
public static String postParams(String url, Map<String, String> params, Map<String, String> header) {
String result = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost request = new HttpPost(url);
CloseableHttpResponse response;
try {
if (params != null) {
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(addParams(params), "UTF-8");
request.setEntity(uefEntity);
}
addHeader(header, request);
response = httpClient.execute(request);
if (response == null) {
return null;
}
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static List<BasicNameValuePair> addParams(Map<String, String> map) {
List<BasicNameValuePair> formParams = new ArrayList<>();
if (map != null) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
return formParams;
}
private static void addHeader(Map<String, String> map, HttpPost post) {
if (map != null) {
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
post.setHeader(entry.getKey(), entry.getValue());
}
}
}
public static void main(String[] args) {
String url = "https://www.baidu.com";
Map<String, String> para = new HashMap<>();
Map<String, String> header = new HashMap<>();
String s = postParams(url, para, header);
System.out.println(s);
}
}