http請求工具類

來源:互聯網
上載者:User

標籤:報文   apache   http請求   name   stat   sage   class   tin   響應報文   

import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpTools {

private HttpTools(){}

private static final Logger logger = Logger.getLogger(HttpTools.class);

public static String httpGet(String url,String charset){
logger.debug("發送 http get 請求 , URL : " + url);
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.connect();
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("發送GET請求出現異常!", e);
}
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
logger.error(e2.getMessage(),e2);
}
}
logger.debug("響應報文: " + result);
return result;
}

public static String httpGet(String url){
return httpGet(url,"UTF-8");
}

public static String httpPost(String url, String data){
return httpPost(url, data,"UTF-8");
}

public static String httpPost(String url, String data,String charset){
logger.debug("發送 http post 請求 , URL : " + url);
logger.debug("請求體: " + data);
OutputStream out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setDoOutput(true);
conn.setDoInput(true);
out = conn.getOutputStream();
out.write(data.getBytes(charset));
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
logger.error("發送 POST 請求出現異常!", e);
}
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
logger.error(ex.getMessage(),ex);
}
}
logger.debug("響應報文: " + result);
return result;
}

}

http請求工具類

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.