HttpURLConnection 表单提交数据

Android 专栏收录该内容
45 篇文章 1 订阅

转载于:https://blog.csdn.net/yongwoozzang/article/details/83029128

HttpURLConnection x-www-form-urlencoded

 
public static String Post(String httpUrl, String data) {
	PrintWriter out = null;
	InputStream readStream = null;
	String output = data;
	String result = "";
 
	try {
		output = "value1=" + URLEncoder.encode(output, "UTF-8");
	} catch (UnsupportedEncodingException e1) {
		e1.printStackTrace();
	}
 
	try {
		URL postUrl = new URL(httpUrl);
		HttpURLConnection conn = (HttpURLConnection) postUrl.openConnection();
		conn.setConnectTimeout(5000);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("Connection", "Keep-Alive");
		conn.setRequestProperty("Charset", "UTF-8");
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//关键代码 application/x-www-form-urlencoded
		out = new PrintWriter(conn.getOutputStream());
		out.print(output);
		out.flush();
		out.close();
		if (conn.getResponseCode() != 200) {
			throw new Exception("请求url失败");
		}
		readStream = conn.getInputStream();
		result = ll.InputStreamToString(readStream);
 
		return result;
	} catch (Exception e) {
		e.printStackTrace();
		result = ll.InputStreamToString(readStream);
		return result;
	} finally {
		if (out != null) {
			out.close();
		}
		if (readStream != null) {
			try {
				readStream.close();
			} catch (IOException e) {
				return null;
			}
		}
	}
}

 

  • 0
    点赞
  • 2
    评论
  • 0
    收藏
  • 扫一扫,分享海报

评论 2 您还未登录,请先 登录 后发表或查看评论
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值