http 方式請求pos請求和get請求,認證方式 使用者名稱密碼
阿新 • • 發佈:2018-12-09
利用apache包請求get和post請求,使用者名稱和密碼認證,使用者名稱密碼填則認證,不填測不認證
利用maven構建專案 需要匯入一個包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
package com.fashion.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; 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.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.io.InputStream; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * ...................................... * .沒有才怎麼懷才不遇,沒有志怎麼壯志難酬 . * . .................................... * *@Author: lq *@Date: 2018/10/10 14:21 *@Description: http pos請求 */ public class HttpUtil { public static String post(String url,Object obj,String userName,String password,String headType) { //此處新增賬號和密碼 CredentialsProvider credentialsProvider = null; if (userName != null && password !=null) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(getHost(url),AuthScope.ANY_PORT) ,new UsernamePasswordCredentials(userName,password)); } CloseableHttpClient httpClient = null; String content = null; try { //設定請求超時時間 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000) .setConnectionRequestTimeout(600000).build(); // httpClient例項. httpClient = HttpClients.custom() //此處可以新增許可權 .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig) .build(); //建立Http post請求 HttpPost httpPost = new HttpPost(url); //設定請求頭 可以設定多個 // Map<String,Object> headParams = new HashMap<>(); // headParams.put("Content-Type", "text/plain"); if (headType == null) { httpPost.addHeader("Content-Type", "application/json;charset=UTF-8"); }else { httpPost.addHeader("Content-Type", "text/plain"); } //設定請求主體 if (obj != null) { StringEntity body = null; if (obj instanceof String || obj instanceof JSONObject) { body = new StringEntity(obj.toString(),"UTF-8"); }else { body = new StringEntity(JSON.toJSONString(obj),"UTF-8"); } httpPost.setEntity(body); } // 執行請求 final long beginTime = System.currentTimeMillis(); // http響應結果 CloseableHttpResponse response = httpClient.execute(httpPost); //log.info("Http request completed Url:{},spend time{} ",url,System.currentTimeMillis() - beginTime); //jsonObject.put("Code",response.getStatusLine().getStatusCode()); //得到請求主體 HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { content = EntityUtils.toString(responseEntity); } System.out.println("當前花費時間:【"+ (System.currentTimeMillis() - beginTime) + "】毫秒"); } catch (Exception e) { e.printStackTrace(); } finally { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } return content; } /** * 傳送get請求 * @param url * @return */ public static String sendGet(String url) { String content = ""; // 建立 httpclient 物件 HttpClient httpclient = HttpClients.custom().build(); //建立請求方式,因為是get請求,所以可以在url後面連線請求引數 HttpGet httpget= new HttpGet(url); try{ // 執行請求,獲取響應資料 HttpResponse response = httpclient.execute(httpget); // 獲取請求實體, HttpEntity responseEntity = response.getEntity(); // 獲取返回例項的內容的長度 long len= responseEntity.getContentLength(); // 獲取 content type Header head= responseEntity.getContentType(); String bodys= head.toString(); System.out.println("內容長度"+len +"head 內容"+bodys); //例項流的獲取 if (responseEntity != null) { content = EntityUtils.toString(responseEntity); InputStream input = responseEntity.getContent(); byte []buffer= new byte[2048]; input.read(buffer); String body= new String(buffer,"utf-8"); JSONObject json = JSONObject.parseObject(body); } }catch(Exception e){ e.printStackTrace(); }finally{ httpget.releaseConnection(); } return content; } public static String getHost(final String url) { if (url == null || "".equals(url.trim())) { return ""; } String host = ""; final Pattern p = Pattern.compile("(?<=//|)((\\w)+\\.)+\\w+"); final Matcher matcher = p.matcher(url); if (matcher.find()) { host = matcher.group(); } return host; }
2.引數說明
使用者名稱和密碼傳則有認證沒有則不認證
headType預設是json格式
3.測試