简单http请求发送,可以自己设置contentType,跨域等信息
importjava.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; 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.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; /** * Http工具 */ public class HttpUtil { /** * 简单post文本 * @param url 请求地址 * @param text 请求内容 */ public static String simplePost( String url , String text ){ try { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(url ); StringEntity se = new StringEntity( text ); se.setContentType( "text/xml;charset=utf-8" ); httppost.setEntity( se ); httppost.addHeader( "Content-Type","application/json" ); CloseableHttpResponse response = httpclient.execute( httppost ); HttpEntity entity = response.getEntity(); String html = EntityUtils. toString( entity, "utf-8" ); httppost.releaseConnection(); return html ; } catch (Exception e ) { throw new RuntimeException( e ); } } /** * 简单post文本 * @param url 请求地址 * @param text 请求内容 */ public static String simplePost( String url , String text, Map<String, String> headMap ){ try { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost httppost = new HttpPost(url ); StringEntity se = new StringEntity( text ); se.setContentType( "text/xml;charset=utf-8" ); httppost.setEntity( se ); if( headMap != null ){ for( String hk : headMap .keySet() ){ httppost.addHeader( hk, headMap.get(hk ) ); } } CloseableHttpResponse response = httpclient.execute( httppost ); HttpEntity entity = response.getEntity(); String html = EntityUtils. toString( entity, "utf-8" ); httppost.releaseConnection(); return html ; } catch (Exception e ) { throw new RuntimeException( e ); } } /** * ajax 请求get 方式 * @param url * @return */ public static String simpleGet( String url ){ try { CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(url ); httpget.setHeader( "Access-Control-Allow-Origin","*" ); CloseableHttpResponse response = httpclient.execute( httpget ); HttpEntity entity = response.getEntity(); String html = EntityUtils. toString( entity, "utf-8" ); httpget.releaseConnection(); return html ; } catch (Exception e ) { throw new RuntimeException( e ); } } }