Java 呼叫http介面
阿新 • • 發佈:2018-12-29
public static void main(String[] args) throws Exception {
//請求的webservice的url
URL url = new URL("http://");
//建立http連結
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//設定請求的方法型別
httpURLConnection.setRequestMethod("POST");
//設定請求的內容型別
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//設定傳送資料
httpURLConnection.setDoOutput(true);
//設定接受資料
httpURLConnection.setDoInput(true);
//傳送資料,使用輸出流
OutputStream outputStream = httpURLConnection.getOutputStream();
//傳送的soap協議的資料
String requestXmlString = requestXml("北京");
String content = "user_id="+ URLEncoder.encode("13846", "gbk");
//傳送資料
outputStream.write(content.getBytes());
//接收資料
InputStream inputStream = httpURLConnection.getInputStream();
//定義位元組陣列
byte[] b = new byte[1024];
//定義一個輸出流儲存接收到的資料
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//開始接收資料
int len = 0;
while (true) {
len = inputStream.read(b);
if (len == -1) {
//資料讀完
break;
}
byteArrayOutputStream.write(b, 0, len);
}
//從輸出流中獲取讀取到資料(服務端返回的)
String response = byteArrayOutputStream.toString();
System.out.println(response);
}
//請求的webservice的url
URL url = new URL("http://");
//建立http連結
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//設定請求的方法型別
httpURLConnection.setRequestMethod("POST");
//設定請求的內容型別
httpURLConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
//設定傳送資料
httpURLConnection.setDoOutput(true);
//設定接受資料
httpURLConnection.setDoInput(true);
//傳送資料,使用輸出流
OutputStream outputStream = httpURLConnection.getOutputStream();
//傳送的soap協議的資料
String requestXmlString = requestXml("北京");
String content = "user_id="+ URLEncoder.encode("13846", "gbk");
//傳送資料
outputStream.write(content.getBytes());
//接收資料
InputStream inputStream = httpURLConnection.getInputStream();
//定義位元組陣列
byte[] b = new byte[1024];
//定義一個輸出流儲存接收到的資料
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//開始接收資料
int len = 0;
while (true) {
len = inputStream.read(b);
if (len == -1) {
//資料讀完
break;
}
byteArrayOutputStream.write(b, 0, len);
}
//從輸出流中獲取讀取到資料(服務端返回的)
String response = byteArrayOutputStream.toString();
System.out.println(response);
}