zoukankan      html  css  js  c++  java
  • httpclient请求服务的各种方法实例

    <!--话不多说,直接上代码-->

    import com.csis.ConfigManager
    import com.csis.io.web.DefaultConfigItem
    import net.sf.json.JSONObject
    import org.apache.commons.lang.StringUtils
    import org.apache.http.*
    import org.apache.http.client.ClientProtocolException
    import org.apache.http.client.HttpClient
    import org.apache.http.client.config.RequestConfig
    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.conn.ssl.NoopHostnameVerifier
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory
    import org.apache.http.entity.StringEntity
    import org.apache.http.entity.mime.MultipartEntityBuilder
    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 org.slf4j.Logger
    import org.slf4j.LoggerFactory

    import javax.net.ssl.SSLContext
    import javax.net.ssl.TrustManager
    import javax.net.ssl.X509TrustManager
    import java.security.cert.CertificateException
    import java.security.cert.X509Certificate

    /**
    * HTTP GET方法
    * @param urlWithParams url和参数
    * @return 返回字符串UTF-8
    * @throws Exception
    */
    public static String httpGet(String urlWithParams) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet(urlWithParams);
    CloseableHttpResponse response = null;
    String resultStr = null;
    try {
    //配置请求的超时设置
    RequestConfig requestConfig = RequestConfig.custom()
    .setConnectionRequestTimeout(50)
    .setConnectTimeout(50)
    .setSocketTimeout(60000).build();
    httpget.setConfig(requestConfig);

    response = httpclient.execute(httpget);
    logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode());
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    HttpEntity entity = response.getEntity();
    if (entity) resultStr = EntityUtils.toString(entity, "utf-8");
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    throw ex;
    } finally {
    httpget.releaseConnection();
    httpclient.close();
    if (response) response.close();
    }
    resultStr
    }

    /**
    * HTTP POST方法
    * @param url 请求路径
    * @param formData 参数,map格式键值对
    * @return 返回字符串UTF-8
    * @throws ClientProtocolException
    * @throws IOException
    */
    static String httpPost(String url, Map<String, String> formData) throws ClientProtocolException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(url);
    CloseableHttpResponse response = null;
    String resultStr = null;
    try {
    if (formData) {
    List<NameValuePair> formParams = new ArrayList<NameValuePair>();
    formData.each { key, value ->
    formParams.add(new BasicNameValuePair(key, value));
    }
    httppost.setEntity(new UrlEncodedFormEntity(formParams, 'utf-8'));
    }
    response = httpclient.execute(httppost);
    logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode());
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    HttpEntity entity = response.getEntity();
    if (entity) resultStr = EntityUtils.toString(entity, "utf-8");
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    throw ex;
    } finally {
    httppost.releaseConnection();
    httpclient.close();
    if (response) response.close();
    }
    resultStr
    }

    static String httpPostFile(String url, File file) throws ClientProtocolException, IOException {
    if (file == null || !file.exists() || StringUtils.isBlank(url)) {
    println("file not exists");
    return null;
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    CloseableHttpResponse response = null;
    try {
    // FileBody fileBody = new FileBody(file);
    MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
    multipartEntityBuilder.addBinaryBody("file", file);
    post.setEntity(multipartEntityBuilder.build());
    response = httpclient.execute(post);
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
    return EntityUtils.toString(entity);
    }
    }
    } catch (Exception ex) {
    ex.printStackTrace();
    } finally {
    post.releaseConnection();
    httpclient.close();
    response.close();
    }
    return null;
    }

    static JSONObject doPost(String url, JSONObject json) {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost post = new HttpPost(url);
    JSONObject response = null;
    try {
    StringEntity s = new StringEntity(json.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");//发送json数据需要设置contentType
    post.setEntity(s);
    HttpResponse res = httpclient.execute(post);
    if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
    String result = EntityUtils.toString(res.getEntity());// 返回json格式:
    response = JSONObject.fromObject(result);
    }
    } catch (Exception e) {
    throw new RuntimeException(e);
    }
    return response;
    }

    static httpGetFile(String url,String path){
    if(!url) return null
    CloseableHttpClient httpclient
    if(url.startsWith("https")){
    httpclient = httpsClient() as CloseableHttpClient
    }else {
    httpclient = HttpClients.createDefault()
    }
    HttpGet httpget = new HttpGet(url)
    CloseableHttpResponse response = null
    try {
    //配置请求的超时设置
    RequestConfig requestConfig = RequestConfig.custom()
    .setConnectionRequestTimeout(50)
    .setConnectTimeout(50)
    .setSocketTimeout(60000).build()
    httpget.setConfig(requestConfig)

    response = httpclient.execute(httpget)
    logger.debug("StatusCode -> " + response.getStatusLine().getStatusCode())
    if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
    HttpEntity entity = response.getEntity()
    if(entity != null) {
    InputStream inputStream = entity.getContent()
    File file
    if(path){
    file = new File(path)
    if(file.isDirectory()){
    file = new File("${file.path}/${System.currentTimeMillis()}")
    }
    }else {
    String fileName = null
    Header contentHeader = response.getFirstHeader("Content-Disposition")
    if(contentHeader){
    HeaderElement[] values = contentHeader.getElements()
    if(values){
    NameValuePair param = values[0].getParameterByName("filename")
    if(param){
    fileName = param.value
    }
    }
    }

    if(!fileName){
    fileName = "${System.currentTimeMillis()}"
    }

    file = new File("${ConfigManager.instance.get(DefaultConfigItem.IO_UPLOAD_PATH)}/${fileName}")
    }

    FileOutputStream fos = new FileOutputStream(file)
    byte[] buffer = new byte[4096]
    int len
    while((len = inputStream.read(buffer) )!= -1){
    fos.write(buffer, 0, len)
    }
    fos.close()
    inputStream.close()

    return file.absolutePath
    }
    }
    } catch (Exception ex) {
    ex.printStackTrace()
    } finally {
    httpget.releaseConnection()
    httpclient.close()
    if (response) response.close()
    }

    null
    }

    private static HttpClient httpsClient() {
    try {
    SSLContext ctx = SSLContext.getInstance("TLS")
    X509TrustManager tm = new X509TrustManager() {
    X509Certificate[] getAcceptedIssuers() {
    return null
    }

    void checkClientTrusted(X509Certificate[] arg0,
    String arg1) throws CertificateException {
    }

    void checkServerTrusted(X509Certificate[] arg0,
    String arg1) throws CertificateException {
    }
    }
    ctx.init(null, [tm] as TrustManager[], null)
    SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(
    ctx, NoopHostnameVerifier.INSTANCE)
    CloseableHttpClient httpclient = HttpClients.custom()
    .setSSLSocketFactory(ssf).build()
    return httpclient
    } catch (Exception e) {
    return HttpClients.createDefault()
    }
    }


    public static String dealCons(String param, String input, String url) {
    String output = "";
    try {
    String reqUrl = url;
    URL restServiceURL = new URL(reqUrl);
    HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL
    .openConnection();
    // param 输入小写,转换成 GET POST DELETE PUT
    httpConnection.setRequestMethod(param.toUpperCase());
    if ("post".equals(param)) {
    // 打开输出开关
    httpConnection.setDoOutput(true);
    // 传递参数
    // String input = "&jsonStr="+URLEncoder.encode(jsonStr, "UTF-8");
    OutputStream outputStream = httpConnection.getOutputStream();
    outputStream.write(input.getBytes());
    outputStream.flush();
    }
    if (httpConnection.getResponseCode() != 200) {
    throw new RuntimeException(
    "HTTP GET Request Failed with Error code : "+httpConnection.getResponseCode());
    }
    BufferedReader responseBuffer = new BufferedReader(
    new InputStreamReader((httpConnection.getInputStream())));
    // 结果集
    output = responseBuffer.readLine();
    println(httpConnection.getResponseCode()+"====================="+output);
    httpConnection.disconnect();
    } catch (MalformedURLException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return output;
    }

  • 相关阅读:
    3.1 history跳转页面产生跨域问题
    2021年6月7日 团队冲刺第二阶段04
    2021年6月6日 团队冲刺第二阶段03
    2021年6月5日 团队冲刺第二阶段02
    2021年6月4日 团队冲刺第二阶段01
    2021年6月3日
    2021年6月2日
    2021年6月1日
    2021年5月31日
    2021年5月30日
  • 原文地址:https://www.cnblogs.com/panca/p/10682009.html
Copyright © 2011-2022 走看看