java实现http post提交

public class Test {

	/**
	 * @param args
	 * @throws UnsupportedEncodingException 
	 */
	public static void main(String[] args) throws UnsupportedEncodingException {
		Map<String,String> parames = new HashMap<String, String>();
		parames.put("addr", "中文");
		String output = http("http://127.0.0.1:8080/simple/index.jsp", parames);
		System.out.println(output);

	}


	public static String http(String url, Map<String, String> params) throws UnsupportedEncodingException {
		URL u = null;
		HttpURLConnection con = null;
		StringBuffer sb = new StringBuffer();
		String paramStr = null;
		if (params != null) {
			for (Entry<String, String> e : params.entrySet()) {
				sb.append(e.getKey());
				sb.append("=");
				sb.append(URLEncoder.encode(e.getValue(), "utf-8") );
				sb.append("&");
			}
			if (sb.length()>0) {
				paramStr = sb.substring(0, sb.length() - 1);
            } else {
            	paramStr = sb.toString();
            }
		}
		System.out.println("url: " + url);
		System.out.println("data: " + paramStr);
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod("POST");
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
			osw.write(paramStr);
			osw.flush();
			osw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}

		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
				buffer.append("\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return buffer.toString();
	}

}

猜你喜欢

转载自isitlikethat.iteye.com/blog/2206772