java利用URL发送get和post请求
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpSender {
public static void main(String[] args) {
}
/**
* 向指定URL发送GET方法的请求
*/
public static String sendGet(String url, String param) throws UnsupportedEncodingException, IOException {
return sendGet(url, param, null);
}
public static String sendGet(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
String result = "";
BufferedReader in = null;
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
//设置超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(15000);
// 设置通用的请求属性
if (header!=null) {
Iterator<Entry<String, String>> it =header.entrySet().iterator();
while(it.hasNext()){
Entry<String, String> entry = it.next();
System.out.println(entry.getKey()+":::"+entry.getValue());
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if (in != null) {
in.close();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*/
public static String sendPost(String url, String param) throws UnsupportedEncodingException, IOException {
return sendPost(url, param, null);
}
public static String sendPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//设置超时时间
conn.setConnectTimeout(5000);
conn.setReadTimeout(15000);
// 设置通用的请求属性
if (header!=null) {
for (Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
return result;
}
}
JAVA发送GET、POST请求,携带请求头,接收解析返回值(通过URL)
参考网址:
https://blog.csdn.net/HezhezhiyuLe/article/details/92395041?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.add_param_isCf
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class SendPostUtil {
/**
* 向指定URL发送GET方法的请求
*/
public static String sendGet(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
String result = "";
BufferedReader in = null;
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
//设置超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(15000);
// 设置通用的请求属性
if (header!=null) {
Iterator<Map.Entry<String, String>> it =header.entrySet().iterator();
while(it.hasNext()){
Map.Entry<String, String> entry = it.next();
System.out.println(entry.getKey()+":"+entry.getValue());
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应,设置utf8防止中文乱码
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if (in != null) {
in.close();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*/
public static String sendPost(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
//设置超时时间
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
// 设置通用的请求属性
if (header!=null) {
for (Map.Entry<String, String> entry : header.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(), "utf8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
return result;
}
}
工具类调用
@Scheduled(cron = "0 0/1 0/1 * * ? ")
public void scheduleSynchronizationAuthAccount(){
//post请求
String str = "http://test1.huaxing.com/oauth/token?client_id=58dbe06586975980379d33b0fe23c55ce07545f935c10cb95a3805a422ea6e91&client_secret=b5e59e55878776724673d78ba35cd23bba2462f7da88c2fa1471b2a5f6da5f7c&grant_type=client_credentials";
// authOrganizationsController.synchronizationAuthAccount(str);
try {
//发送POST
String tokenstr = SendPostUtil.sendPost(str, null, null);
System.out.println("tokenstr"+tokenstr);
//解析POST返回参数
JSONObject parse = (JSONObject)JSONObject.parse(tokenstr);
//获取TOKEN
String access_token = parse.getString("access_token");
System.out.println(access_token);
//设置请求头
HashMap<String, String > stringSendGetUtilHashMap = new HashMap<>();
stringSendGetUtilHashMap.put("Authorization","Bearer "+access_token);
String access_token1 = "Bearer "+ access_token;
//人员
//发送GET请求
String getUser="http://test1.huaxing.com/api/get_users";
//发送GET请求
String getback = SendPostUtil.sendGet(getUser,null, stringSendGetUtilHashMap);
//解析返回参数
JSONObject parse2 = (JSONObject)JSONObject.parse(getback);
String userdata = parse2.getString("user_data");
System.out.println(userdata);
System.out.println("------------------------------我是华丽的分割线------------------------------");
//部门
//发送GET请求
String getTeam = "http://test1.huaxing.com/api/get_teams";
//发送GET请求
String getback2 = SendPostUtil.sendGet(getTeam, null, stringSendGetUtilHashMap);
JSONObject parse3 = (JSONObject)JSONObject.parse(getback2);
//解析返回参数
String teamdata = parse3.getString("team_data");
System.out.println(teamdata);
JSONArray userArray = JSONArray.fromObject(userdata);
List<AuthEmployeesJson> authEmployeesJsonList = (List<AuthEmployeesJson>) JSONArray.toCollection(userArray,AuthEmployeesJson.class);
List<AuthEmployees> authEmployeesList = new ArrayList<>();
for (AuthEmployeesJson authEmployeesJson : authEmployeesJsonList) {
AuthEmployees authEmployees = new AuthEmployees();
authEmployees.setId(authEmployeesJson.getId()+"");
authEmployees.setEmployeeCode(authEmployeesJson.getHr_id()+"");
authEmployees.setEmployeeName(authEmployeesJson.getName());
authEmployees.setEnglishName(authEmployeesJson.getEn_name());
authEmployees.setEmail(authEmployeesJson.getEmail());
authEmployees.setOrganizationCode(authEmployeesJson.getTeam_id()+"");
authEmployees.setManageNumber(authEmployeesJson.getId()+"");
authEmployeesList.add(authEmployees);
}
sw.buildQuery()
.doBatchInsert(authEmployeesList);
System.out.println("添加成功");
} catch (IOException e) {
e.printStackTrace();
}
}
注:发送POST请求不好使时,使用工具类2
工具类2
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import com.alibaba.fastjson.JSONObject;
/**
* @Author: zhangle
* @Date: 2019/6/25 14:08
* @Version 1.0
*/
public class URLConnection {
/**
* post请求封装 参数为?a=1&b=2&c=3
* @param path 接口地址
* @param Info 参数
* @return
* @throws IOException
*/
public static JSONObject postResponse(String path,String Info) throws IOException{
//1, 得到URL对象
URL url = new URL(path);
//2, 打开连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//3, 设置提交类型
conn.setRequestMethod("POST");
//4, 设置允许写出数据,默认是不允许 false
conn.setDoOutput(true);
conn.setDoInput(true);//当前的连接可以从服务器读取内容, 默认是true
//5, 获取向服务器写出数据的流
OutputStream os = conn.getOutputStream();
//参数是键值队 , 不以"?"开始
os.write(Info.getBytes());
//os.write("googleTokenKey=&username=admin&password=5df5c29ae86331e1b5b526ad90d767e4".getBytes());
os.flush();
//6, 获取响应的数据
//得到服务器写回的响应数据
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8"));
String str = br.readLine();
JSONObject json = JSONObject.parseObject(str);
System.out.println("响应内容为: " + json);
return json;
}
/**
* post请求封装 参数为{"a":1,"b":2,"c":3}
* @param path 接口地址
* @param Info 参数
* @return
* @throws IOException
*/
public static JSONObject postResponse(String path,JSONObject Info) throws IOException{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(path);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(Info.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
post.setEntity(s);
// 发送请求
HttpResponse httpResponse = client.execute(post);
// 获取响应输入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
System.out.println(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("请求服务器成功,做相应处理");
} else {
System.out.println("请求服务端失败");
}
} catch (Exception e) {
System.out.println("请求异常");
throw new RuntimeException(e);
}
return JSONObject.parseObject(result);
}
}