java发送get post请求_【工具】java发送GET、POST请求
前項目使用這種HTTP的方式進行數據交互,目前已更換數據交互方式,但是作為接口提供調用來說還是比較簡潔高效的:
總體流程就是:
1、發送HTTP請求
2、獲取返回的JSON對象
3、JSON轉換
package com.xx;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
public class SendGetPost {
/**
* 發送get請求
* 參數設置:?param=val?m2=val2
* @author TF
*
*/
public static String sendGet(String url){
String result = "";
BufferedReader in = null;
try {
//創建URL對象、
URL urlGet =new URL(url);
//打開URL連接
URLConnection connection = urlGet.openConnection();
//設置請求頭信息
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
connection.setRequestProperty("contentType", "UTF-8");
//建立連接
connection.connect();
// 獲取所有響應頭字段
Map> map = connection.getHeaderFields();
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 發送post請求
* 參數設置param1=val1&m2=val2
*
* */
public static String sendPost(String url,String param){
String result = "";
BufferedReader in = null;
OutputStreamWriter out = null;
try {
//創建URL對象、
URL urlPost = new URL(url);
//打開URL連接
URLConnection connection = urlPost.openConnection();
HttpURLConnection conn = (HttpURLConnection) connection;
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0");
conn.setRequestMethod("POST");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new OutputStreamWriter(conn.getOutputStream(),"UTF-8");
// 發送請求參數
out.write(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (MalformedURLException e) {
System.out.println("error");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
總結
以上是生活随笔為你收集整理的java发送get post请求_【工具】java发送GET、POST请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: fedora java环境变量_Fedo
- 下一篇: java nio2 iocp_基于JDK