java http xml请求_java发送HTTP请求(XML格式的报文)

这是一个Java类,名为HttpSendUtil,用于发送HTTP POST请求。它接收一个URL字符串和XML信息,通过打开连接,设置请求属性,写入数据并读取响应来实现通信。如果连接被拒绝,它会返回特定错误信息。
摘要由CSDN通过智能技术生成

package io.renren.common.utils;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.net.ConnectException;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

/**

* 发送HTTP的一种方法

* GaoLiang

*/

public class HttpSendUtil {

public static String testPost(String urlStr, String xmlInfo) {

try {

URL url = new URL(urlStr);

URLConnection con = url.openConnection();

con.setDoOutput(true);

// con.setRequestProperty("Pragma:", "no-cache");

// con.setRequestProperty("Cache-Control", "no-cache");

// 一定要设置报文格式,否则发送失败

con.setRequestProperty("Content-Type", "text/xml");

OutputStreamWriter out = null;

try {

out = new OutputStreamWriter(con.getOutputStream());

} catch (ConnectException e) {

// e.printStackTrace();

return "Connection refused";

}

// System.out.println("urlStr=" + urlStr);

// System.out.println("xmlInfo=" + xmlInfo);

out.write(new String(xmlInfo.getBytes("ISO-8859-1")));

out.flush();

out.close();

BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

StringBuilder stringBuilder = new StringBuilder();

String line = "";

for (line = br.readLine(); line != null; line = br.readLine()) {

// System.out.println(line);

stringBuilder.append(line);

}

return stringBuilder.toString();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return null;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值