Get请求不带参数
传入的数据是个Url,如果有需要可以添加其他header信息,返回String类型的返回值。
/*** * get请求 * @param url * @return String */ public static String doGet(String url) { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); String result = null; try { get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } return result; }
Get请求带参数
Get请求的参数会附带在链接的后面,这里传入的参数是url和hashmap键值对,如果有需要可以添加其他header信息,返回String类型的返回值。
/*** * get请求(带参数) * @param url * @return String */ public static String doGet(String url,HashMap params) { String result = null; try { URIBuilder uriBuilder=new URIBuilder(url); Iterator maplist=params.entrySet().iterator(); while (maplist.hasNext()){ Map.Entry map= (Map.Entry) maplist.next(); uriBuilder.addParameter(map.getKey(),map.getValue()); } CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(uriBuilder.build()); get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); HttpResponse response = client.execute(get); result = EntityUtils.toString(response.getEntity(), "UTF-8"); } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
Post请求(JSON格式的参数)
传入的参数是String类型的url和params参数,params参数需要的是json对象转换后的String字符串
/** * post 请求(用于请求 json 格式的参数) * @param url * @param params * @return */ public static String doPost(String url, String params) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url);// 创建 httpPost httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-Type", "application/json"); String charSet = "UTF-8"; StringEntity entity = new StringEntity(params, charSet); httpPost.setEntity(entity); CloseableHttpResponse response = null; try { response = httpclient.execute(httpPost); StatusLine status = response.getStatusLine(); int state = status.getStatusCode(); if (state == HttpStatus.SC_OK) { HttpEntity responseEntity = response.getEntity(); String jsonString = EntityUtils.toString(responseEntity); return jsonString; } else{ } } finally { if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
Post请求(form格式的参数)
请求的参数是String类型的url和Hashmap键值对,键值对中存放from的键和值
/*** * post请求(用于处理form格式的数据) * @param url * @param map * @return * @throws Exception */ public static String doPost(String url, HashMap map) throws Exception { String result = ""; CloseableHttpClient client = null; CloseableHttpResponse response = null; RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000) .setConnectionRequestTimeout(550000).build(); client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); // client = HttpClients.createDefault(); URIBuilder uriBuilder = new URIBuilder(url); HttpPost httpPost = new HttpPost(uriBuilder.build()); httpPost.setHeader("Connection", "Keep-Alive"); httpPost.setHeader("Charset", CHARSET_UTF8); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); Iterator> it = map.entrySet().iterator(); List params = new ArrayList(); while (it.hasNext()) { Map.Entry entry = it.next(); NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue()); params.add(pair); } httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); try { response = client.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, CHARSET_UTF8); } } } catch (ClientProtocolException e) { throw new RuntimeException("创建连接失败" + e); } catch (IOException e) { throw new RuntimeException("创建连接失败" + e); } return result; }
总结
可以把上面的四个方法封装到自己的NetUtil工具类中,以后再用的时候就很方便了。