java 常见几种发送http请求案例
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; /**
* @Description:发送http请求帮助类
* @author:liuyc
* @time:2016年5月17日 下午3:25:32
*/
public class HttpClientHelper {
/**
* @Description:使用HttpURLConnection发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:26:07
*/
public static String sendPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
// 发送请求
try {
URL url = new URL(urlParam);
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (sbParams != null && sbParams.length() > 0) {
osw = new OutputStreamWriter(con.getOutputStream(), charset);
osw.write(sbParams.substring(0, sbParams.length() - 1));
osw.flush();
}
// 读取返回内容
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
} return resultBuffer.toString();
} /**
* @Description:使用URLConnection发送post
* @author:liuyc
* @time:2016年5月17日 下午3:26:52
*/
public static String sendPost2(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> e : params.entrySet()) {
sbParams.append(e.getKey());
sbParams.append("=");
sbParams.append(e.getValue());
sbParams.append("&");
}
}
URLConnection con = null;
OutputStreamWriter osw = null;
BufferedReader br = null;
try {
URL realUrl = new URL(urlParam);
// 打开和URL之间的连接
con = realUrl.openConnection();
// 设置通用的请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
con.setDoOutput(true);
con.setDoInput(true);
// 获取URLConnection对象对应的输出流
osw = new OutputStreamWriter(con.getOutputStream(), charset);
if (sbParams != null && sbParams.length() > 0) {
// 发送请求参数
osw.write(sbParams.substring(0, sbParams.length() - 1));
// flush输出流的缓冲
osw.flush();
}
// 定义BufferedReader输入流来读取URL的响应
resultBuffer = new StringBuffer();
int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
if (contentLength > 0) {
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:发送get请求保存下载文件
* @author:liuyc
* @time:2016年5月17日 下午3:27:29
*/
public static void sendGetAndSaveFile(String urlParam, Map<String, Object> params, String fileSavePath) {
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
BufferedReader br = null;
FileOutputStream os = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
InputStream is = con.getInputStream();
os = new FileOutputStream(fileSavePath);
byte buf[] = new byte[1024];
int count = 0;
while ((count = is.read(buf)) != -1) {
os.write(buf, 0, count);
}
os.flush();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
os = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
} /**
* @Description:使用HttpURLConnection发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:27:29
*/
public static String sendGet(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
HttpURLConnection con = null;
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
} finally {
if (con != null) {
con.disconnect();
con = null;
}
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用URLConnection发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:27:58
*/
public static String sendGet2(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
BufferedReader br = null;
try {
URL url = null;
if (sbParams != null && sbParams.length() > 0) {
url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
} else {
url = new URL(urlParam);
}
URLConnection con = url.openConnection();
// 设置请求属性
con.setRequestProperty("accept", "*/*");
con.setRequestProperty("connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立连接
con.connect();
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用HttpClient发送post请求
* @author:liuyc
* @time:2016年5月17日 下午3:28:23
*/
public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlParam);
// 构建请求参数
List<NameValuePair> list = new ArrayList<NameValuePair>();
Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, Object> elem = iterator.next();
list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
}
BufferedReader br = null;
try {
if (list.size() > 0) {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
httpPost.setEntity(entity);
}
HttpResponse response = client.execute(httpPost);
// 读取服务器响应数据
resultBuffer = new StringBuffer();
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用HttpClient发送get请求
* @author:liuyc
* @time:2016年5月17日 下午3:28:56
*/
public static String httpClientGet(String urlParam, Map<String, Object> params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
BufferedReader br = null;
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
try {
sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
sbParams.append("&");
}
}
if (sbParams != null && sbParams.length() > 0) {
urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
}
HttpGet httpGet = new HttpGet(urlParam);
try {
HttpResponse response = client.execute(httpGet);
// 读取服务器响应数据
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp;
resultBuffer = new StringBuffer();
while ((temp = br.readLine()) != null) {
resultBuffer.append(temp);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
br = null;
throw new RuntimeException(e);
}
}
}
return resultBuffer.toString();
} /**
* @Description:使用socket发送post请求
* @author:liuyc
* @time:2016年5月18日 上午9:26:22
*/
public static String sendSocketPost(String urlParam, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlParam);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("POST " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} /**
* @Description:使用socket发送get请求
* @author:liuyc
* @time:2016年5月18日 上午9:27:18
*/
public static String sendSocketGet(String urlParam, Map<String, Object> params, String charset) {
String result = "";
// 构建请求参数
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry<String, Object> entry : params.entrySet()) {
sbParams.append(entry.getKey());
sbParams.append("=");
sbParams.append(entry.getValue());
sbParams.append("&");
}
}
Socket socket = null;
OutputStreamWriter osw = null;
InputStream is = null;
try {
URL url = new URL(urlParam);
String host = url.getHost();
int port = url.getPort();
if (-1 == port) {
port = 80;
}
String path = url.getPath();
socket = new Socket(host, port);
StringBuffer sb = new StringBuffer();
sb.append("GET " + path + " HTTP/1.1\r\n");
sb.append("Host: " + host + "\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
// 这里一个回车换行,表示消息头写完,不然服务器会继续等待
sb.append("\r\n");
if (sbParams != null && sbParams.length() > 0) {
sb.append(sbParams.substring(0, sbParams.length() - 1));
}
osw = new OutputStreamWriter(socket.getOutputStream());
osw.write(sb.toString());
osw.flush();
is = socket.getInputStream();
String line = null;
// 服务器响应体数据长度
int contentLength = 0;
// 读取http响应头部信息
do {
line = readLine(is, 0, charset);
if (line.startsWith("Content-Length")) {
// 拿到响应体内容长度
contentLength = Integer.parseInt(line.split(":")[1].trim());
}
// 如果遇到了一个单独的回车换行,则表示请求头结束
} while (!line.equals("\r\n"));
// 读取出响应体数据(就是你要的数据)
result = readLine(is, contentLength, charset);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (osw != null) {
try {
osw.close();
} catch (IOException e) {
osw = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
throw new RuntimeException(e);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
throw new RuntimeException(e);
}
}
}
}
}
return result;
} /**
* @Description:读取一行数据,contentLe内容长度为0时,读取响应头信息,不为0时读正文
* @time:2016年5月17日 下午6:11:07
*/
private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
List<Byte> lineByte = new ArrayList<Byte>();
byte tempByte;
int cumsum = 0;
if (contentLength != 0) {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
cumsum++;
} while (cumsum < contentLength);// cumsum等于contentLength表示已读完
} else {
do {
tempByte = (byte) is.read();
lineByte.add(Byte.valueOf(tempByte));
} while (tempByte != 10);// 换行符的ascii码值为10
} byte[] resutlBytes = new byte[lineByte.size()];
for (int i = 0; i < lineByte.size(); i++) {
resutlBytes[i] = (lineByte.get(i)).byteValue();
}
return new String(resutlBytes, charset);
} }
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.Socket;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.URLEncoder;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Map.Entry;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.message.BasicNameValuePair;
- /**
- * @Description:发送http请求帮助类
- * @author:liuyc
- * @time:2016年5月17日 下午3:25:32
- */
- public class HttpClientHelper {
- /**
- * @Description:使用HttpURLConnection发送post请求
- * @author:liuyc
- * @time:2016年5月17日 下午3:26:07
- */
- public static String sendPost(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> e : params.entrySet()) {
- sbParams.append(e.getKey());
- sbParams.append("=");
- sbParams.append(e.getValue());
- sbParams.append("&");
- }
- }
- HttpURLConnection con = null;
- OutputStreamWriter osw = null;
- BufferedReader br = null;
- // 发送请求
- try {
- URL url = new URL(urlParam);
- con = (HttpURLConnection) url.openConnection();
- con.setRequestMethod("POST");
- con.setDoOutput(true);
- con.setDoInput(true);
- con.setUseCaches(false);
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- if (sbParams != null && sbParams.length() > 0) {
- osw = new OutputStreamWriter(con.getOutputStream(), charset);
- osw.write(sbParams.substring(0, sbParams.length() - 1));
- osw.flush();
- }
- // 读取返回内容
- resultBuffer = new StringBuffer();
- int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
- if (contentLength > 0) {
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:使用URLConnection发送post
- * @author:liuyc
- * @time:2016年5月17日 下午3:26:52
- */
- public static String sendPost2(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> e : params.entrySet()) {
- sbParams.append(e.getKey());
- sbParams.append("=");
- sbParams.append(e.getValue());
- sbParams.append("&");
- }
- }
- URLConnection con = null;
- OutputStreamWriter osw = null;
- BufferedReader br = null;
- try {
- URL realUrl = new URL(urlParam);
- // 打开和URL之间的连接
- con = realUrl.openConnection();
- // 设置通用的请求属性
- con.setRequestProperty("accept", "*/*");
- con.setRequestProperty("connection", "Keep-Alive");
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 发送POST请求必须设置如下两行
- con.setDoOutput(true);
- con.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- osw = new OutputStreamWriter(con.getOutputStream(), charset);
- if (sbParams != null && sbParams.length() > 0) {
- // 发送请求参数
- osw.write(sbParams.substring(0, sbParams.length() - 1));
- // flush输出流的缓冲
- osw.flush();
- }
- // 定义BufferedReader输入流来读取URL的响应
- resultBuffer = new StringBuffer();
- int contentLength = Integer.parseInt(con.getHeaderField("Content-Length"));
- if (contentLength > 0) {
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- }
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:发送get请求保存下载文件
- * @author:liuyc
- * @time:2016年5月17日 下午3:27:29
- */
- public static void sendGetAndSaveFile(String urlParam, Map<String, Object> params, String fileSavePath) {
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- HttpURLConnection con = null;
- BufferedReader br = null;
- FileOutputStream os = null;
- try {
- URL url = null;
- if (sbParams != null && sbParams.length() > 0) {
- url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
- } else {
- url = new URL(urlParam);
- }
- con = (HttpURLConnection) url.openConnection();
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.connect();
- InputStream is = con.getInputStream();
- os = new FileOutputStream(fileSavePath);
- byte buf[] = new byte[1024];
- int count = 0;
- while ((count = is.read(buf)) != -1) {
- os.write(buf, 0, count);
- }
- os.flush();
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (os != null) {
- try {
- os.close();
- } catch (IOException e) {
- os = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- }
- }
- /**
- * @Description:使用HttpURLConnection发送get请求
- * @author:liuyc
- * @time:2016年5月17日 下午3:27:29
- */
- public static String sendGet(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- HttpURLConnection con = null;
- BufferedReader br = null;
- try {
- URL url = null;
- if (sbParams != null && sbParams.length() > 0) {
- url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
- } else {
- url = new URL(urlParam);
- }
- con = (HttpURLConnection) url.openConnection();
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.connect();
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- } finally {
- if (con != null) {
- con.disconnect();
- con = null;
- }
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:使用URLConnection发送get请求
- * @author:liuyc
- * @time:2016年5月17日 下午3:27:58
- */
- public static String sendGet2(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- BufferedReader br = null;
- try {
- URL url = null;
- if (sbParams != null && sbParams.length() > 0) {
- url = new URL(urlParam + "?" + sbParams.substring(0, sbParams.length() - 1));
- } else {
- url = new URL(urlParam);
- }
- URLConnection con = url.openConnection();
- // 设置请求属性
- con.setRequestProperty("accept", "*/*");
- con.setRequestProperty("connection", "Keep-Alive");
- con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
- // 建立连接
- con.connect();
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:使用HttpClient发送post请求
- * @author:liuyc
- * @time:2016年5月17日 下午3:28:23
- */
- public static String httpClientPost(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- HttpClient client = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(urlParam);
- // 构建请求参数
- List<NameValuePair> list = new ArrayList<NameValuePair>();
- Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
- while (iterator.hasNext()) {
- Entry<String, Object> elem = iterator.next();
- list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
- }
- BufferedReader br = null;
- try {
- if (list.size() > 0) {
- UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
- httpPost.setEntity(entity);
- }
- HttpResponse response = client.execute(httpPost);
- // 读取服务器响应数据
- resultBuffer = new StringBuffer();
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
- String temp;
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:使用HttpClient发送get请求
- * @author:liuyc
- * @time:2016年5月17日 下午3:28:56
- */
- public static String httpClientGet(String urlParam, Map<String, Object> params, String charset) {
- StringBuffer resultBuffer = null;
- HttpClient client = new DefaultHttpClient();
- BufferedReader br = null;
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- try {
- sbParams.append(URLEncoder.encode(String.valueOf(entry.getValue()), charset));
- } catch (UnsupportedEncodingException e) {
- throw new RuntimeException(e);
- }
- sbParams.append("&");
- }
- }
- if (sbParams != null && sbParams.length() > 0) {
- urlParam = urlParam + "?" + sbParams.substring(0, sbParams.length() - 1);
- }
- HttpGet httpGet = new HttpGet(urlParam);
- try {
- HttpResponse response = client.execute(httpGet);
- // 读取服务器响应数据
- br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
- String temp;
- resultBuffer = new StringBuffer();
- while ((temp = br.readLine()) != null) {
- resultBuffer.append(temp);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (br != null) {
- try {
- br.close();
- } catch (IOException e) {
- br = null;
- throw new RuntimeException(e);
- }
- }
- }
- return resultBuffer.toString();
- }
- /**
- * @Description:使用socket发送post请求
- * @author:liuyc
- * @time:2016年5月18日 上午9:26:22
- */
- public static String sendSocketPost(String urlParam, Map<String, Object> params, String charset) {
- String result = "";
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- Socket socket = null;
- OutputStreamWriter osw = null;
- InputStream is = null;
- try {
- URL url = new URL(urlParam);
- String host = url.getHost();
- int port = url.getPort();
- if (-1 == port) {
- port = 80;
- }
- String path = url.getPath();
- socket = new Socket(host, port);
- StringBuffer sb = new StringBuffer();
- sb.append("POST " + path + " HTTP/1.1\r\n");
- sb.append("Host: " + host + "\r\n");
- sb.append("Connection: Keep-Alive\r\n");
- sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
- sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
- // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
- sb.append("\r\n");
- if (sbParams != null && sbParams.length() > 0) {
- sb.append(sbParams.substring(0, sbParams.length() - 1));
- }
- osw = new OutputStreamWriter(socket.getOutputStream());
- osw.write(sb.toString());
- osw.flush();
- is = socket.getInputStream();
- String line = null;
- // 服务器响应体数据长度
- int contentLength = 0;
- // 读取http响应头部信息
- do {
- line = readLine(is, 0, charset);
- if (line.startsWith("Content-Length")) {
- // 拿到响应体内容长度
- contentLength = Integer.parseInt(line.split(":")[1].trim());
- }
- // 如果遇到了一个单独的回车换行,则表示请求头结束
- } while (!line.equals("\r\n"));
- // 读取出响应体数据(就是你要的数据)
- result = readLine(is, contentLength, charset);
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- is = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- return result;
- }
- /**
- * @Description:使用socket发送get请求
- * @author:liuyc
- * @time:2016年5月18日 上午9:27:18
- */
- public static String sendSocketGet(String urlParam, Map<String, Object> params, String charset) {
- String result = "";
- // 构建请求参数
- StringBuffer sbParams = new StringBuffer();
- if (params != null && params.size() > 0) {
- for (Entry<String, Object> entry : params.entrySet()) {
- sbParams.append(entry.getKey());
- sbParams.append("=");
- sbParams.append(entry.getValue());
- sbParams.append("&");
- }
- }
- Socket socket = null;
- OutputStreamWriter osw = null;
- InputStream is = null;
- try {
- URL url = new URL(urlParam);
- String host = url.getHost();
- int port = url.getPort();
- if (-1 == port) {
- port = 80;
- }
- String path = url.getPath();
- socket = new Socket(host, port);
- StringBuffer sb = new StringBuffer();
- sb.append("GET " + path + " HTTP/1.1\r\n");
- sb.append("Host: " + host + "\r\n");
- sb.append("Connection: Keep-Alive\r\n");
- sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r\n");
- sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r\n");
- // 这里一个回车换行,表示消息头写完,不然服务器会继续等待
- sb.append("\r\n");
- if (sbParams != null && sbParams.length() > 0) {
- sb.append(sbParams.substring(0, sbParams.length() - 1));
- }
- osw = new OutputStreamWriter(socket.getOutputStream());
- osw.write(sb.toString());
- osw.flush();
- is = socket.getInputStream();
- String line = null;
- // 服务器响应体数据长度
- int contentLength = 0;
- // 读取http响应头部信息
- do {
- line = readLine(is, 0, charset);
- if (line.startsWith("Content-Length")) {
- // 拿到响应体内容长度
- contentLength = Integer.parseInt(line.split(":")[1].trim());
- }
- // 如果遇到了一个单独的回车换行,则表示请求头结束
- } while (!line.equals("\r\n"));
- // 读取出响应体数据(就是你要的数据)
- result = readLine(is, contentLength, charset);
- } catch (Exception e) {
- throw new RuntimeException(e);
- } finally {
- if (osw != null) {
- try {
- osw.close();
- } catch (IOException e) {
- osw = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- is = null;
- throw new RuntimeException(e);
- } finally {
- if (socket != null) {
- try {
- socket.close();
- } catch (IOException e) {
- socket = null;
- throw new RuntimeException(e);
- }
- }
- }
- }
- }
- return result;
- }
- /**
- * @Description:读取一行数据,contentLe内容长度为0时,读取响应头信息,不为0时读正文
- * @time:2016年5月17日 下午6:11:07
- */
- private static String readLine(InputStream is, int contentLength, String charset) throws IOException {
- List<Byte> lineByte = new ArrayList<Byte>();
- byte tempByte;
- int cumsum = 0;
- if (contentLength != 0) {
- do {
- tempByte = (byte) is.read();
- lineByte.add(Byte.valueOf(tempByte));
- cumsum++;
- } while (cumsum < contentLength);// cumsum等于contentLength表示已读完
- } else {
- do {
- tempByte = (byte) is.read();
- lineByte.add(Byte.valueOf(tempByte));
- } while (tempByte != 10);// 换行符的ascii码值为10
- }
- byte[] resutlBytes = new byte[lineByte.size()];
- for (int i = 0; i < lineByte.size(); i++) {
- resutlBytes[i] = (lineByte.get(i)).byteValue();
- }
- return new String(resutlBytes, charset);
- }
- }
java 常见几种发送http请求案例的更多相关文章
- Ajax发送XML请求案例
Ajax发送XML请求需求: 根据输入的国家,输出这些国家下面的城市. 如果请求参数较多,而且请求参数的结构关系复杂,则可以考虑发送XML请求.XML请求的实质还是POST请求,只是在发送请求的客户端 ...
- 【JAVA】通过HttpClient发送HTTP请求的方法
HttpClient介绍 HttpClient 不是一个浏览器.它是一个客户端的 HTTP 通信实现库.HttpClient的目标是发 送和接收HTTP 报文.HttpClient不会去缓存内容,执行 ...
- Java利用原始HttpURLConnection发送http请求数据小结
1,在post请求下,写输出应该在读取之后,否则会抛出异常. 即操作OutputStream对象应该在InputStreamReader之前. 2.conn.getResponseCode()获取返回 ...
- java中原生的发送http请求(无任何的jar包导入)
package com.teamsun.pay.wxpay.util; import java.io.BufferedReader; import java.io.IOException; impor ...
- Ajax发送简单请求案例
所谓简单请求,是指不包含任何参数的请求.这种请求通常用于自动刷新的应用,例如证券交易所的实时信息发送.这种请求通常用于公告性质的响应,公告性质的响应无需客户端的任何请求参数,而是由服务器根据业务数据自 ...
- java常见3种文件上传速度对比和文件上传方法详细代码
在java里面文件上传的方式很多,最简单的依然是FileInputStream.FileOutputStream了,在这里我列举3种常见的文件上传方法代码,并比较他们的上传速度(由于代码是在本地测试, ...
- Java之使用HttpClient发送GET请求
package LoadRunner; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import o ...
- java中两种发起POST请求,并接收返回的响应内容的方式 (转)
http://xyz168000.blog.163.com/blog/static/21032308201162293625569/ 2.利用java自带的java.net.*包下提供的工具类 代码如 ...
- PHP的3种发送HTTP请求的方式
1.CURL方式发送数据及上传文件 <?php class IndexController extends ControllerBase { public function indexActio ...
随机推荐
- CentOS查看何人何时登陆用户
使用linux 的last命令: last命令列出的是/var/log 目录下的wtmp文件内容,这个文件存的是二进制内容,不可以直接用vi等文本边界软件打开.这样即使是root用户也不可能随随便便的 ...
- 对phpexcel的若干补充
导出excel属性设置 //Include class require_once('Classes/PHPExcel.php'); require_once('Classes/PHPExcel/Wri ...
- PHP实现MySQL数据导出为EXCEL(CSV格式)
<?php // 输出Excel文件头,可把user.csv换成你要的文件名 header('Content-Type: application/vnd.ms-excel'); header(' ...
- iOS 数据压缩与解压
转自: http://blog.csdn.net/dkq972958298/article/details/53321804 在实际开发中,我们经常要对比较大的数据进行压缩后再上传服务器,下面是我在项 ...
- datatables隐藏列排序
var tableOption = { id: 'cacScriptTable', order: [[2, 'desc'],[1, 'desc']],//以第三列‘updatedAt’排序,如果第三列 ...
- NHibernate连接oracle报错
NHibernate.Exceptions.GenericADOException:“could not execute query [ select sys_user0_.USERID as USE ...
- 虚幻4 - ARPG实战教程(第一季)
在广受欢迎的的<虚幻4高速开发入门>视频教程之后.我收到了许多的反馈,当中大量的同学想要一个实战类的教程.于是,我花了一段时间准备之后,推出了新的一系列实战教程. 希望以深入浅出的方式.解 ...
- Vs2010创建WebService
在Visual Studio 2010中已经找不到直接创建WebService的模板方式了,但下面的方法可心实现: 在 Visual Studio 2010 的新建 Web 应用程序或者 Web 网站 ...
- SpringBoot(零)-- 工程创建
一.约定优于配置 二.快速创建SoringBoot项目 地址:http://start.spring.io/ 三.在步骤二中,创建好了SpringBootDemo 项目,导入Eclipse 自定义ba ...
- Linux 远程同步:rsync
rsync 简介: (1) rsync 是一个远程数据同步工具,可通过 LAN/WAN 快速同步多台主机间的文件(2) rsync 使用所谓的“rsync算法”来使本地和远程两个主机之间的文件达到同步 ...