通过HttpURLConnection连接服务器,发送报文,获取服务器报文返回

Java 通过HttpURLConnection连接服务器 发送 POST 和 GET 请求

package com.dataservice.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

import javax.net.ssl.HttpsURLConnection;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 通过HttpURLConnection连接服务器,发送报文,获取服务器报文返回
 * 
 * @author xiaoding
 *
 */
@Slf4j
public class SendMess {
  /**
   * 
   * @param content
   *          request content
   * @param charset
   * @param postUrl
   *          post URL
   * @return massage from remote server
   */
  public static String transferData(String content, Charset charset, String postUrl, String conentType) throws IOException {
    HttpURLConnection connection = null;
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    try {
      byte[] postData = content.getBytes(charset);
      int postDataLength = postData.length;
      // 配置连接
      URL url = new URL(postUrl);

      connection = (HttpURLConnection) url.openConnection();
      if (connection instanceof HttpsURLConnection) {
        SslContextUtils.createInstance().initHttpsConnect((HttpsURLConnection) connection);
      }
      // connection.setRequestProperty("Content-type", );
      connection.setConnectTimeout(5000);
      connection.setReadTimeout(20000);
      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setRequestMethod("POST");
      connection.setRequestProperty("Content-Type", conentType);
      connection.setRequestProperty("charset", charset.displayName());
      connection.setRequestProperty("Content-Length", Integer.toString(postDataLength));
      connection.setUseCaches(false);
      // 发送请求
      connection.getOutputStream().write(postData);
      connection.getOutputStream().flush();
      connection.getOutputStream().close();
      // 读取响应
      reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));

      char[] buf = new char[1024];
      int length = 0;
      while ((length = reader.read(buf)) > 0) {
        sb.append(buf, 0, length);
      }
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
      if (reader != null) {
        IOUtils.closeQuietly(reader);
      }
    }
    String res = sb.toString();
    return res;
  }

  public static String sendDataByGet(String url, String params) throws IOException {
    // Create HttpClient Object
    CloseableHttpClient client = HttpClients.createDefault();
    StringBuilder urlString = new StringBuilder();
    urlString.append(url);
    urlString.append("?");
    urlString.append(params);
    String urlReq = urlString.toString();
    log.debug("request url is {}", urlReq);
    // 创建Get方法实例
    HttpGet httpsgets = new HttpGet(urlReq);
    String strRep = "";
    try {
      HttpResponse response = client.execute(httpsgets);
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        strRep = EntityUtils.toString(response.getEntity());
        httpsgets.abort();
      }
    } catch (IOException e) {
      log.error("http request error", e);
      throw e;
    }
    return strRep;
  }
}

调用示例:

String param = "companyCode=" + companyCode + "&productCode=" + productCode + "&str=" + paramJson + "&secretType=" + secretType + "&signType" + signType + "&sign=" + sign";

String resp = SendMess.sendDataByGet(url, param);

String res =  SendMess.transferData(param, DsContent.DATA_CHARSET, url, "application/x-www-form-urlencoded;charset=utf-8");
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值