java发送HTTP请求(XML格式的报文)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
java发送HTTP请求(XML格式的报⽂)package mon.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import .ConnectException;
import .MalformedURLException;
import .URL;
import .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;
}
}。