記錄:Java_POST請求接口實例

/**

* @param URL 訪問地址
* @param params 參數內容
* @param Header 設置/添加請求頭信息key-value
* @param linktime 連接超時 單位毫秒
* @param readtime 讀取超時 單位毫秒
* @return
*/
public  static Map<String,String> mapBoby(String URL,String params,Map<String,String> Header,int linktime,int readtime){
Map<String,String> map=new HashMap<String,String>();
int code=0;
try {
           URL url = new URL(URL);
           HttpURLConnection http=(HttpURLConnection) url.openConnection();
           http.setRequestMethod("POST");// 提交模式
           http.setConnectTimeout(linktime);//連接超時 單位毫秒
           http.setReadTimeout(readtime);//讀取超時 單位毫秒
           http.setDoOutput(true);// 允許輸出,設置是否向httpUrlConnection輸出,因爲這個是post請求,參數要放在 
http.setDoInput(true);// 允許輸入,設置是否從httpUrlConnection讀入,默認情況下是true; 
//http.setRequestProperty("Content-Type", "application/json");//設置請求頭裏面的數據,以下設置用於解決http請求code415的問題
//遍歷添加需要的Header的頭信息
for(String key : Header.keySet()){
http.setRequestProperty(key,Header.get(key));//設置請求頭裏面的數據,
//http.addRequestProperty(key,Header.get(key));//添加Header頭信息
}
http.connect();
DataOutputStream out =new DataOutputStream(http.getOutputStream());//向對象輸出流寫出數據,這些數據將存到內存緩衝區中,字節的方式輸出
out.write(params.getBytes());
out.flush(); //刷新對象輸出流,將任何字節都寫入潛在的流中 
out.close();// 關閉流對象,此時,不能再向對象輸出流寫入任何數據,先前寫入的數據存在於內存緩衝區中   

//往map添加返回信息
code=http.getResponseCode();
map.put("狀態碼code", String.valueOf(code));
//讀取響應狀態
if (code==200){
System.out.println("響應狀態:"+http.getResponseCode());
// 連接發起請求,處理服務器響應
InputStreamReader inputStream =new InputStreamReader(http.getInputStream());
BufferedReader reader = new BufferedReader(inputStream);
String lines;
StringBuffer sbuffer = new StringBuffer();
// 循環讀取流,若不到結尾處 
while ((lines = reader.readLine()) != null) {                
lines = new String(lines.getBytes(), "utf-8");                    
sbuffer.append(lines);

map.put("接口返回信息", sbuffer.toString());
//System.out.println("返回:"+sbuffer.toString());
//System.out.println("返回:"+lines);
reader.close();//關閉流對象
}
//斷開鏈接
http.disconnect();
} catch (Exception e) {
// TODO: handle exception
map.put("狀態碼code", String.valueOf(code));
System.out.println("發送 POST 請求出現異常!");
e.printStackTrace();


}
return map;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章