2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > JAVA发送GET POST请求 携带请求头 接收解析返回值(通过URL)

JAVA发送GET POST请求 携带请求头 接收解析返回值(通过URL)

时间:2021-07-24 09:35:13

相关推荐

JAVA发送GET POST请求 携带请求头 接收解析返回值(通过URL)

前言

Java定时发送请求,获取响应结果,这是一个常见操作。为此封装一个Java类,做发送GET/POST请求,然后解析返回参数。

需要代理发送的小伙伴可以看这篇文章↓↓↓

java/HttpClient:get、post 设置代理(.UnknownHostException)非连接池式

注1:工具类0,1为代码少,2为设置请求头发送,3为2的补充,工具类都可发送Get、Post

注2:如频繁使用Http请求(多线程)建议使用连接池发送java:HTTP连接池,设置代理

注3:发送链接一定要加协议头http/httpsClientProtocolException报错

工具类0(推荐)

直接复制粘贴即可,代码少

import org.apache.http.NameValuePair;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.client.utils.URIBuilder;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;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 .URI;import java.util.ArrayList;import java.util.List;import java.util.Map;public class HttpClientUtil {/*** 发送get请求** @param url 请求URL* @param param 请求参数 key:value url携带参数 或者无参可不填* @return*/public static String doGet(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();String resultString = "";CloseableHttpResponse response = null;try {// 创建uriURIBuilder builder = new URIBuilder(url);if (param != null) {for (String key : param.keySet()) {builder.addParameter(key, param.get(key));}}URI uri = builder.build();// 创建http GET请求HttpGet httpGet = new HttpGet(uri);// 执行请求response = httpClient.execute(httpGet);// 判断返回状态是否为200if (response.getStatusLine().getStatusCode() == 200) {resultString = EntityUtils.toString(response.getEntity(), "UTF-8");}} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpClient.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}/*** 无参数get请求* @param url* @return*/public static String doGet(String url) {return doGet(url, null);}/*** 发送post请求** @param url 请求URL* @param param 请求参数 key:value* @return*/public static String doPost(String url, Map<String, String> param) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建参数列表if (param != null) {List<NameValuePair> paramList = new ArrayList<>();for (String key : param.keySet()) {paramList.add(new BasicNameValuePair(key, param.get(key)));}// 模拟表单UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);httpPost.setEntity(entity);}// 执行http请求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "utf-8");} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpClient.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return resultString;}/*** 发送post 请求** @param url 请求地址* @param json 请求参数* @return*/public static String doPostJson(String url, String json) {// 创建Httpclient对象CloseableHttpClient httpClient = HttpClients.createDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建请求内容StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);httpPost.setEntity(entity);// 执行http请求response = httpClient.execute(httpPost);resultString = EntityUtils.toString(response.getEntity(), "utf-8");} catch (Exception e) {e.printStackTrace();} finally {try {if (response != null) {response.close();}httpClient.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return resultString;}}

工具类1(推荐)

直接复制粘贴即可,最少代码,工具类23代码繁杂

import org.apache.http.HttpEntity;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;import org.slf4j.LoggerFactory;import java.io.IOException;/*** @Author ZhangLe* @Date /11/25 12:33*/public class HttpsClient {private CloseableHttpClient httpClient;private HttpGet httpGet;public static final String CONTENT_TYPE = "Content-Type";/*** 发送get请求* @param url 发送链接 拼接参数 http://localhost:8090/order?a=1* @return* @throws IOException*/public String sendGet(String url) throws IOException {httpClient = HttpClients.createDefault();httpGet = new HttpGet(url);CloseableHttpResponse response = httpClient.execute(httpGet);String resp;try {HttpEntity entity = response.getEntity();resp = EntityUtils.toString(entity, "utf-8");EntityUtils.consume(entity);} finally {response.close();}LoggerFactory.getLogger(getClass()).info(" resp:{}", resp);return resp;}/*** 创建发送post实体* @param charset消息编码* @param contentType 消息体内容类型, HttpsClient.CONTENT_TYPE 调用传默认值* @param url 请求地址* @param data 发送数据* @return* @throws IOException*/public String sendPost(String charset, String contentType, String url,String data) throws Exception {HttpClient httpclient = com.picc.wechat.HttpsClient.getInstance();HttpPost httpPost = new HttpPost(url);httpPost.setHeader(CONTENT_TYPE, contentType);httpPost.setEntity(new StringEntity(data, charset));CloseableHttpResponse response = (CloseableHttpResponse) httpclient.execute(httpPost);String resp = null;try {HttpEntity entity = response.getEntity();resp = EntityUtils.toString(entity, charset);EntityUtils.consume(entity);} finally {response.close();}LoggerFactory.getLogger(getClass()).info("call [{}], param:{}, resp:{}", url, data, resp);return resp;}}

工具类2(不推荐)

设置请求头

参考原作者文章

import java.io.*;import .URL;import .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;}}

工具类2调用

此工具类只做知识了解,知道需要配置的东西即可

@Scheduled(cron = "0 0/1 0/1 * * ? ")public void scheduleSynchronizationAuthAccount(){//post请求String str = "/oauth/token?client_id=58dbe06586975980379d33b0fe23c55ce07545f935c10cb95a3805a422ea6e91&client_secret=b5e59e55878776724673d78ba35cd23bba2462f7da88c2fa1471b2a5f6da5f7c&grant_type=client_credentials";// authOrganizationsController.synchronizationAuthAccount(str);try {//发送POSTString tokenstr = SendPostUtil.sendPost(str, null, null);System.out.println("tokenstr"+tokenstr);//解析POST返回参数JSONObject parse = (JSONObject)JSONObject.parse(tokenstr);//获取TOKENString 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="/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 = "/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();}}

注:发送工具类2POST请求不好使时,使用工具类3

工具类3(不推荐)

此工具类只做知识了解

参考

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import .HttpURLConnection;import .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: /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, 设置允许写出数据,默认是不允许 falseconn.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);}}

祝你幸福

送你一首歌:《让我们荡起双桨》 中央人民广播电台少年广播合唱团

附图:让我们荡起双桨,一块划水(北师大三年级语文上册 八 成长的经历)😃 😃 😃

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。