基于HttpClient实现
基本思路都是一样的,通过HttpResponse实例获得请求返回的数据体,具体数据封装在HttpEntity对象中。
/**
* Created by Song on 2016/11/28.
* 基于HttpClient提供网络访问工具
*/
public final class NetUtil {
public static CloseableHttpClient httpClient = HttpClientBuilder.create().build();
/**
* get请求获取String类型数据
* @param url 请求链接
* @return
*/
public static String get(String url){
StringBuffer sb = new StringBuffer();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(httpGet); //1
HttpEntity entity = response.getEntity();
InputStreamReader reader = new InputStreamReader(entity.getContent(),"utf-8");
char [] charbufer;
while (0<reader.read(charbufer=new char[10])){
sb.append(charbufer);
}
}catch (IOException e){//1
e.printStackTrace();
}finally {
httpGet.releaseConnection();
}
return sb.toString();
}
/**
* post方式请求数据
* @param url 请求链接
* @param data post数据体
* @return
*/
public static String post(String url, Map<String,String> data){
StringBuffer sb = new StringBuffer();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
if(null != data) {
for (String key : data.keySet()) {
valuePairs.add(new BasicNameValuePair(key, data.get(key)));
}
}
try {
httpPost.setEntity(new UrlEncodedFormEntity(valuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
BufferedInputStream bis = new BufferedInputStream(httpEntity.getContent());
byte [] buffer;
while (0<bis.read(buffer=new byte[128])){
sb.append(new String(buffer,"utf-8"));
}
}catch (UnsupportedEncodingException e){//数据格式有误
e.printStackTrace();
}catch (IOException e){//请求出错
e.printStackTrace();
}finally {
httpPost.releaseConnection();
}
return sb.toString();
}
}
- 基于Java net工具包
基本思路是通过HttpURLConnection 对象设置网络连接参数,建立网络连接,与获得请求返回的网络数据输入流,并从中获得数据。对于JSON格式的数据体,可进一步封装为JSONObject。
import net.sf.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 实现GET以及POST请求
* mail:1147649695@qq.com
*/
public class UrlReqUtil {
public static JSONObject get(String url){
HttpURLConnection http = null;
InputStream is = null;
try {
URL urlGet = new URL(url);
http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
System.setProperty("sun.net.client.defaultReadTimeout", "30000");
http.connect();
is =http.getInputStream();
int size =is.available();
byte[] jsonBytes =new byte[size];
is.read(jsonBytes);
String message=new String(jsonBytes,"UTF-8");
return JSONObject.fromObject(message);
} catch (Exception e) {
return null;
}finally {
if(null != http) http.disconnect();
try {
if (null != is) is.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
public static String post(String url,String data){
HttpURLConnection http = null;
PrintWriter out = null;
BufferedReader reader = null;
try {
//创建连接
URL urlPost = new URL(url);
http = (HttpURLConnection) urlPost
.openConnection();
http.setDoOutput(true);
http.setDoInput(true);
http.setRequestMethod("POST");
http.setUseCaches(false);
http.setInstanceFollowRedirects(true);
http.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
http.connect();
//POST请求
OutputStreamWriter outWriter = new OutputStreamWriter(http.getOutputStream(), "utf-8");
out = new PrintWriter(outWriter);
out.print(data);
out.flush();
out.close();
out = null;
//读取响应
reader = new BufferedReader(new InputStreamReader(
http.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
reader.close();
reader = null;
System.out.println(sb.toString());
return sb.toString();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}finally {
if(null != http) http.disconnect();
if(null != out) out.close();
try{
if(null != reader) reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}