java发送http请求 utf8,Java使用原生的HttpURLConnection发送http请求

/**

* 发送http请求

* @param message 发送的内容

* @param snedUrl 请求的url

* @return

*/

public static String sendRequest(String message, String snedUrl) {

log.error("发送http请求 url:" + snedUrl + ",message:" + message);

StringBuffer str = new StringBuffer();

HttpURLConnection conn = null;

try {

URL url = new URL(snedUrl);

conn = (HttpURLConnection) url.openConnection();

//是否打开输入流 , 此方法默认为true

conn.setDoInput(true);

//是否打开输出流, 此方法默认为false

conn.setDoOutput(true);

//POST或者GET

conn.setRequestMethod("POST");

//GET支持缓存,POST不支持

conn.setUseCaches(false);

//连接超时时间 10s

conn.setConnectTimeout(10000);

//read超时时间 120s

conn.setReadTimeout(120000);

//表示连接

conn.connect();

//写入发送的数据(POST请求的时候才需要)

OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");

out.write(message);

out.flush();

out.close();

//判断请求返回的状态

if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

//读取返回的数据

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

String temp = null;

while ((temp = in.readLine()) != null) {

str.append(temp);

}

in.close();

}

} catch (Exception e) {

log.error("发送http请求失败:" + e);

} finally {

if (null != conn) {

conn.disconnect();

}

}

log.info("http请求返回的数据:" + str.toString());

return str.toString();

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值