import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map; /**
* HTTP请求类
* @author
*/
public class HttpInvoker { /**
* GET请求
* @param getUrl
* @throws IOException
* @return 提取HTTP响应报文包体,以字符串形式返回
*/
public static String httpGet(String getUrl) throws IOException {
//1 把字符串形式的网址转成 java.net.URL对象
URL getURL = new URL(getUrl);
/*
* 2 通过java.net.URL打开一个连接(获取一个代表与远程对象的URLConnection对象),并转为 HttpURLConnection ,
Returns a URLConnection object that represents a connection
to the remote object referred to by the URL.
*/
HttpURLConnection connection = (HttpURLConnection) getURL.openConnection();
//3 通过HttpURLConnection对象真正获取连接
connection.connect();
//4 连接后那么这个远程连接对象就可以通过自身的一些方法读取到连接的信息了,这里是把流转成字符串
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sbStr = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sbStr.append(line);
}
bufferedReader.close();
connection.disconnect();
return new String(sbStr.toString().getBytes(),"utf-8");
} public static void main(String[] args) throws IOException {
String url = "https://www.hao123.com/?tn=99682755_hao_pg";
String rtn_json = httpGet(url);
System.out.println(""+rtn_json);
} /**
* POST请求
* @param postUrl
* @param postHeaders
* @param postEntity
* @throws IOException
* @return 提取HTTP响应报文包体,以字符串形式返回
*/
public static String httpPost(String postUrl,Map<String, String> postHeaders, String postEntity) throws IOException { URL postURL = new URL(postUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) postURL.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setUseCaches(false);
httpURLConnection.setInstanceFollowRedirects(true);
httpURLConnection.setRequestProperty(" Content-Type ", " application/x-www-form-urlencoded "); if(postHeaders != null) {
for(String pKey : postHeaders.keySet()) {
httpURLConnection.setRequestProperty(pKey, postHeaders.get(pKey));
}
}
if(postEntity != null) {
DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
out.writeBytes(postEntity);
out.flush();
out.close(); // flush and close
}
//connection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder sbStr = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sbStr.append(line);
}
bufferedReader.close();
httpURLConnection.disconnect();
return new String(sbStr.toString().getBytes(),"utf-8");
} }