post請求方式寫法

public static String send(String url,String data) throws DJException{
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost post = null;
		CloseableHttpResponse response=null;
		try {
			post = new HttpPost(url);  // 請求方法Post
			StringEntity entity = new StringEntity(data,"utf-8");
			entity.setContentEncoding("UTF-8");    // 字符編碼
			entity.setContentType("application/json");   // json類型
			post.setEntity(entity);
			response =httpClient.execute(post);
			int statusCode=	response.getStatusLine().getStatusCode(); // 返回的狀態碼
			if(statusCode == 200) {
				HttpEntity he = response.getEntity();
				return EntityUtils.toString(he, "UTF-8");
			}else{
				throw new DJException("服務器連接異常statusCode:"+statusCode);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new DJException("請求失敗:"+e.getMessage());
		}finally {
			try {
				response.close();
				httpClient.close();
			} catch (IOException e) {
			}	
		}
		
	}

其他資料:https://www.cnblogs.com/hanyj123/p/9641626.html

https://www.cnblogs.com/shengwei/p/5527394.html

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