자바 몇 가지 http 요청 방식 (post / get)
7082 단어 자바
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// URL
URLConnection conn = realUrl.openConnection();
//
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// POST
conn.setDoOutput(true);
conn.setDoInput(true);
// URLConnection
out = new PrintWriter(conn.getOutputStream());
//
out.print(param);
// flush
out.flush();
// BufferedReader URL
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" POST !"+e);
e.printStackTrace();
}
// finally 、
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
2. HttpURLConnection (POST) 사용
public static String postTo(String strURL, String params) {
try {
URL url = new URL(strURL);//
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestMethod("POST"); //
connection.setRequestProperty("Accept", "application/text"); //
connection.setRequestProperty("Content-Type", "application/text"); //
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GBK"); // utf-8
out.append(params);
out.flush();
out.close();
//
int length = (int) connection.getContentLength();//
InputStream is = connection.getInputStream();
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
String result = new String(data, "GBK"); // utf-8
System.out.println(result);
return result;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "error"; //
}
3. HTTPClient (POST) 를 사용 합 니 다. 그 중에서 매개 변 수 는 키 쌍 이 고 반환 값 은 바이트 배열 입 니 다.
@SuppressWarnings("unchecked")
public static byte[] doHttpRequest(String host, Map<String, String> params)
throws IOException {
byte[] bt = null;
Map<String, String> map = null == params ? new HashMap<String, String>()
: params;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(host);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Entry<String, String>) it.next();
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));
HttpResponse response = httpclient.execute(httpost);
if (200 != response.getStatusLine().getStatusCode()) {
throw new RuntimeException("http "
+ response.getStatusLine().getStatusCode());
}
InputStream in = response.getEntity().getContent();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int temp;
byte[] buf = new byte[1024];
while ((temp = in.read(buf, 0, buf.length)) != -1) {
bos.write(buf, 0, temp);
}
bt = bos.toByteArray();
return bt;
}
4 、 httpclient get 요청, String 으로 되 돌아 가기
public static String getHttpRequestContent(String serialUrl, String encode)
throws ClientProtocolException, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(serialUrl);
HttpResponse response = httpclient.execute(httpGet);
if (200 != response.getStatusLine().getStatusCode()) {
throw new RuntimeException("http "
+ response.getStatusLine().getStatusCode());
}
HttpEntity entity = response.getEntity();
InputStreamReader in = new InputStreamReader(entity.getContent(),
encode == null ? HTTP.UTF_8 : encode);
BufferedReader reader = new BufferedReader(in);
String line = null;
String content = "";
while (null != (line = reader.readLine())) {
content += line;
}
in.close();
reader.close();
httpclient.getConnectionManager().shutdown();
return content;
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Is Eclipse IDE dying?In 2014 the Eclipse IDE is the leading development environment for Java with a market share of approximately 65%. but ac...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.