http protocol request request: satisfy the parameter setting and request header setting

/**
	 * Post方式请求,返回Json数据
	 * @param requestUrl	请求地址
	 * @param requestParams	请求参数
	 * @param heads 请求头
	 * @return
	 */
	public static String sendRequestByPostWithHead(String requestUrl, Map<String, String> requestParams,HashMap<String,String> heads){
    
    
		HttpURLConnection connection=null;
		String response = null;
		try {
    
    
			Set<String> paramKeys = requestParams.keySet();
			int i = 0;
			String data = "";
			for(String paramKey : paramKeys){
    
    
				if(i == 0){
    
    
					data = paramKey + "=" + requestParams.get(paramKey);
				}else{
    
    
					data = data + "&" + paramKey + "=" + requestParams.get(paramKey);
				}
				i++;
			}
			logger.info("Request url:"+requestUrl);
			logger.info("Request data:"+data);
			//创建连接
			// Send the request
			URL url = new URL(requestUrl);
			connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			connection.setRequestProperty("Charset", "UTF-8");
			connection.setDoOutput(true);
			Iterator<String> iter = heads.keySet().iterator();
			while(iter.hasNext()){
    
    
				String key = (String) iter.next();
				connection.setRequestProperty(key, heads.get(key));
			}
			OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());

			//write parameters
			writer.write(data);
			writer.flush();

			// Get the response
			StringBuffer answer = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
    
    
				answer.append(line);
			}
			writer.close();
			reader.close();

			response = answer.toString();
			//断开连接
			connection.disconnect();
		} catch (MalformedURLException e) {
    
    
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
    
    
			e.printStackTrace();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
		return response;
	}

Guess you like

Origin blog.csdn.net/qq_42258975/article/details/111211132