Java利用HttpURLConnection发送post请求

Posted skinchqqhah

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java利用HttpURLConnection发送post请求相关的知识,希望对你有一定的参考价值。

URL url = null;
HttpURLConnection http = null;

try {
	url = new URL(urls);
	http = (HttpURLConnection) url.openConnection();
	http.setDoInput(true);
	http.setDoOutput(true);
	http.setUseCaches(false);
	http.setConnectTimeout(50000);//设置连接超时
//如果在建立连接之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。
	http.setReadTimeout(50000);//设置读取超时
//如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。			
	http.setRequestMethod("POST");
	// http.setRequestProperty("Content-Type","text/xml; charset=UTF-8");
	http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	http.connect();
	param = "&appName=" + appName 
			+ "&token=" + token 
			+ "&method=" + method 
			+ "&dataType=" + dataType 
			+ "&dataParams=" + dataParams 
			+ "&sign=" + sign;

	OutputStreamWriter osw = new OutputStreamWriter(http.getOutputStream(), "utf-8");
	osw.write(param);
	osw.flush();
	osw.close();

	if (http.getResponseCode() == 200) {
		BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream(), "utf-8"));
		String inputLine;
		while ((inputLine = in.readLine()) != null) {
			result += inputLine;
		}
		in.close();
		//result = "["+result+"]";
	}
} catch (Exception e) {
	System.out.println("err");
} finally {
	if (http != null) http.disconnect();
	if (fis != null) fis.close();
}

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow


以上是关于Java利用HttpURLConnection发送post请求的主要内容,如果未能解决你的问题,请参考以下文章

java使用HttpURLConnection发送Post数据

java 使用原生HttpURLConnection发送post请求

关于JAVA发送Https请求(HttpsURLConnection和HttpURLConnection)

Java-使用HttpURLConnection发送GET,POST请求

java 发送 http 请求练习两年半(HttpURLConnection)

使用 Java HttpUrlConnection 发送带有令牌的 GET 请求