public class Test {
/**
* @param args
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws UnsupportedEncodingException {
Map parames = new HashMap();
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 params) throws UnsupportedEncodingException {
URL u = null;
HttpURLConnection con = null;
StringBuffer sb = new StringBuffer();
String paramStr = null;
if (params != null) {
for (Entry 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();
}
}