关于使用Java原生API编写发送HTTP_POST请求的工具类的具体代码:
[java] package com.jadyer.http; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * 使用Java原生API编写发送HTTP_POST请求的工具类 * @see 本工具类仅用于学习了解,实际中推荐使用HttpClientUtil工具类 * @see 地址为http://blog.csdn.net/jadyer/article/details/8087960 * @create Mar 4, 2013 2:47:57 PM * @author 玄玉<http://blog.csdn/net/jadyer> */ public class NativeHTTPUtil { private NativeHTTPUtil(){} /** * 发送HTTP_POST请求 * @see 若发送的<code>sendData</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code> * @see 本方法默认的连接和读取超时均为30秒 * @param reqURL 请求地址 * @param sendData 发送到远程主机的正文数据 * @return HTTP响应码`远程主机响应正文,如<code>"200`SUCCESS"</code><br>若通信过程中发生异常则返回"HTTP响应码`Failed",如<code>"500`Failed"</code> */ public static String sendPostRequest(String reqURL, String sendData){ HttpURLConnection httpURLConnection = null; OutputStream out = null; //写 InputStream in = null; //读 int responseCode = 0; //远程主机响应的HTTP状态码 try{ URL sendUrl = new URL(reqURL); httpURLConnection = (HttpURLConnection)sendUrl.openConnection(); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setDoOutput(true); //指示应用程序要将数据写入URL连接,其值默认为false httpURLConnection.setUseCaches(false); httpURLConnection.setConnectTimeout(30000); //30秒连接超时 httpURLConnection.setReadTimeout(30000); //30秒读取超时