java發送HTTP請求(XML格式的報文)


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;
}

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM