java httppost_java实现http post提交

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();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值