模擬post請求 json格式傳參

/**
	 * 模擬post請求    json參數
	 * @param params  json字符串
	 * @return
	 */
public JSONArray getResponse(StringJson params) {

		String response = null;
		String url = "";
	    try {
	        CloseableHttpClient httpclient = null;
	        CloseableHttpResponse httpresponse = null;
	        try {
	            httpclient = HttpClients.createDefault();
	            HttpPost httppost = new HttpPost(url);
	            httppost.setHeader("Content-Type","application/json");
	            StringEntity stringentity = new StringEntity(params,
	                    ContentType.create("text/json", "UTF-8"));
	            httppost.setEntity(stringentity);
	            httppost.getAllHeaders();
	            httpresponse = httpclient.execute(httppost);
	            response = EntityUtils
	                    .toString(httpresponse.getEntity());

	        } finally {
	            if (httpclient != null) {
	                httpclient.close();
	            }
	            if (httpresponse != null) {
	                httpresponse.close();
	            }
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
		return JSONArray.fromObject(response);
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章