HttpURLConnection Post

/**
	 * Http访问
	 * @param httpUrl String
	 * @param parameters Map<String,String>
	 * @return String
	 * @throws IOException
	 */
	public static synchronized String httpClient(String httpUrl,Map<String,String> parameters) throws IOException {
		URL url = new URL(httpUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setUseCaches(false);
		StringBuffer result = new StringBuffer();
		InputStreamReader reader = null;
		BufferedReader bufReader = null;
		try {
			StringBuffer params = new StringBuffer();
			if (parameters != null && parameters.size() > 0) {
				conn.setDoOutput(true);
				for (Map.Entry<String, String> parameter:parameters.entrySet()) {
					String key = parameter.getKey();
					String value = parameter.getValue();
					params.append("&" + key + "=" + value);
				}
				params.substring(1);
				OutputStream output = conn.getOutputStream();
				output.write(params.toString().getBytes());
			}
			InputStream input = conn.getInputStream();
			reader = new InputStreamReader(input);
			bufReader = new BufferedReader(reader);
			while (true) {
				String line = bufReader.readLine();
				if (line == null) {
					break;
				}
				result.append(line);
			}
		} 
		catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		finally {
			if (bufReader != null) {
				bufReader.close();
			}
			if (reader != null) {
				reader.close();
			}
		}
		return result.toString();
	}

 

你可能感兴趣的:(HttpURLConnection Post)