http跨域請求
阿新 • • 發佈:2019-01-09
package com.cn.jg.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.cn.jg.util.GlobalNameUtil; public class HttpClientUtil { private static final Logger LOG = LoggerFactory.getLogger(HttpClientUtil.class); public static String getHttpData(HttpServletRequest req,String url) { HttpClient client = HttpClients.custom().build(); HttpUriRequest request = RequestBuilder.get().setUri(url) .setHeader(HttpHeaders.CONTENT_TYPE, "application/json").setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader(GlobalNameUtil.DEFAULT_USER,GlobalNameUtil.DEFAULT_PASS)).build(); HttpResponse response; String data=null; try { response = client.execute(request); data=EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e1) { LOG.info("http協議錯誤 ",e1); e1.printStackTrace(); } catch (IOException e1) { LOG.info("http網路異常 ",e1); e1.printStackTrace(); } return data; } private static String authorizationHeader(final String username, final String password) { final String auth = username + ":" + password; final byte[] encodedAuth = Base64.encodeBase64(auth.getBytes()); return "Basic " + new String(encodedAuth); } public static void main(String[] args) { System.out.println(authorizationHeader("pub","pub")); } public static String postHttpDatas(HttpServletRequest req,String url,String value) throws UnsupportedEncodingException { HttpClient client = HttpClients.custom().build(); //value json型別的資料 轉換成entity實體傳輸 StringEntity datas=new StringEntity(value,"utf-8"); //url請求路徑 HttpUriRequest request = RequestBuilder.post().setUri(url).setEntity(datas) //設定字元編碼 並設定http Authorization http basic認證 .setHeader(HttpHeaders.CONTENT_TYPE, "application/json").setHeader(HttpHeaders.AUTHORIZATION, authorizationHeader(GlobalNameUtil.DEFAULT_USER,GlobalNameUtil.DEFAULT_PASS)).build(); HttpResponse response; String data=null; try { response = client.execute(request); //獲取請求的資料 data=EntityUtils.toString(response.getEntity()); } catch (ClientProtocolException e1) { LOG.info("http協議錯誤 ",e1); e1.printStackTrace(); } catch (IOException e1) { LOG.info("http網路異常 ",e1); e1.printStackTrace(); } return data; } }