자바 에서 흔히 볼 수 있 는 몇 가지 http 요청 사례
20479 단어 자바 개발
import java.io.BufferedReader;
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 params, String charset) {
StringBuffer resultBuffer = null;
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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 params, String charset) {
StringBuffer resultBuffer = null;
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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 params, String fileSavePath) {
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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 params, String charset) {
StringBuffer resultBuffer = null;
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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 params, String charset) {
StringBuffer resultBuffer = null;
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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 params, String charset) {
StringBuffer resultBuffer = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(urlParam);
//
List list = new ArrayList();
Iterator> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
Entry 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 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 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 params, String charset) {
String result = "";
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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
");
sb.append("Host: " + host + "\r
");
sb.append("Connection: Keep-Alive\r
");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r
");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r
");
// , ,
sb.append("\r
");
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
"));
// ( )
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 params, String charset) {
String result = "";
//
StringBuffer sbParams = new StringBuffer();
if (params != null && params.size() > 0) {
for (Entry 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
");
sb.append("Host: " + host + "\r
");
sb.append("Connection: Keep-Alive\r
");
sb.append("Content-Type: application/x-www-form-urlencoded; charset=utf-8 \r
");
sb.append("Content-Length: ").append(sb.toString().getBytes().length).append("\r
");
// , ,
sb.append("\r
");
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
"));
// ( )
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 lineByte = new ArrayList();
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);
}
}
위의 4 가지 방법 은 get 과 post 요청 을 보 낼 수 있 는 방법 입 니 다. 1 번: HttpURLConnection, 2 번: URLConnection, 3 번: HttpClient, 4 번 째: Socket, 여러분 이 주의해 야 할 것 은 3 번 째 HttpClient 를 사용 할 때 세 개의 jar 가방 에 의존 해 야 한 다 는 것 입 니 다. 각각 apache - httpcoponents - httpclient. jar, comons - logging - 1.0.4. jar, httpcore - 4.1.1. jar 입 니 다.자, 여기까지 하 겠 습 니 다. 문제 가 있 으 면 메 시 지 를 남 겨 주세요.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 에서 흔히 볼 수 있 는 몇 가지 http 요청 사례위의 4 가지 방법 은 get 과 post 요청 을 보 낼 수 있 는 방법 입 니 다. 1 번: HttpURLConnection, 2 번: URLConnection, 3 번: HttpClient, 4 번 째: Soc...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.