在我们开发项目时,经常会涉及到网络交互这一块,很多时候都是多人同时开发一个项目。因此一个好的架构师,通常会在搭建框架时,会构建一个统一的IO工具类,进行网络交互,这样便于统一管理。如果每个人写一套自己的IO网络交互,则会显得杂乱。有点重复发明轮子的感觉。好了,题外话不多说,下面附上我经常使用的IO网络交互工具类代码,仅供参考交流。
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
public class IoUtil {
// 网络连接超时时间
private static final int DEF_CONN_TIMEOUT = 30 * 1000;
// 网络sock通信超时时间
private static final int DEF_SOCKET_TIMEOUT = 30 * 1000;
/**
* post请求获取服务端数据
*/
public static String responseFromServiceByPost(String url,
HashMap<String, String> map) {
if (url == null || url.equals("") || map == null) {
return null;
}
HttpPost httpPost = null;
URI encodedUri = null;
try {
encodedUri = new URI(url);
httpPost = new HttpPost(encodedUri);
} catch (URISyntaxException e) {
// 清理一些空格
String encodedUrl = url.replace(' ', '+');
httpPost = new HttpPost(encodedUrl);
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
DEF_SOCKET_TIMEOUT);
try {
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey().toString();
String value = null;
if (entry.getValue() == null) {
value = "";
} else {
value = entry.getValue().toString();
}
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(
key, value);
nameValuePair.add(basicNameValuePair);
}
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "GBK")); // 此处也可以改为UTF-8
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse != null) {
int code = httpResponse.getStatusLine().getStatusCode();
if (code == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity).trim();
return result;
} else {
httpPost.abort();
}
} else {
httpPost.abort();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
return null;
}
/**
* get请求获取服务端数据
*/
public static String responseFromServiceByGet(String url,
HashMap<String, String> map) {
if (url == null || url.equals("")) {
return null;
}
if (map != null) {
StringBuilder sb = new StringBuilder(url);
sb.append('?');
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey().toString();
String value = null;
if (entry.getValue() == null) {
value = "";
} else {
value = entry.getValue().toString();
}
sb.append(key);
sb.append('=');
try {
value = URLEncoder.encode(value, HTTP.UTF_8);
sb.append(value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sb.append('&');
}
sb.deleteCharAt(sb.length() - 1);// 删除最后一个"&"
url = sb.toString();
}
HttpGet httpGet = null;
URI encodedUri = null;
InputStream is = null;
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
} catch (URISyntaxException e) {
// 清理一些空格
String encodedUrl = url.replace(' ', '+');
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
DEF_SOCKET_TIMEOUT);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null) {
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
is = entity.getContent();
if (is != null) {
return getStr1FromInputstream(is);
}
} else {
httpGet.abort();
}
} else {
httpGet.abort();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
return null;
}
/**
* 判断网络线路状态
*/
public static boolean checkNetworkIsGood(String url) {
if (url == null || url.equals("")) {
return false;
}
HttpGet httpGet = null;
URI encodedUri = null;
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
} catch (URISyntaxException e) {
// 清理一些空格
String encodedUrl = url.replace(' ', '+');
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
5000);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null) {
int uRC = httpResponse.getStatusLine().getStatusCode();
if (uRC == HttpStatus.SC_OK) {
return true;
} else {
httpGet.abort();
}
} else {
httpGet.abort();
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
return false;
}
// 把inputstream转换为字符串(方法一)
private static String getStr1FromInputstream(InputStream input) {
String result = null;
int i = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
while ((i = input.read()) != -1) {
baos.write(i);
}
result = baos.toString();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}