安卓网络访问
String data1 = URLEncoder.encode(data, "utf-8");
中文传参,先将中文编码,免得乱码
public static InputStream getInputStreamByPost(String urlPath, Map<String, String> params, String encoding) {
try {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (null != encoding) {
sb.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),encoding));
} else {
sb.append(entry.getKey()).append("=").append(entry.getValue());
}
sb.append("&");
}
String data = sb.deleteCharAt(sb.length() - 1).toString();
URL url;
url = new URL(urlPath);
// 打开连接
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
// 设置提交方式
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
// post方式不能使用缓存
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// 设置连接超时
conn.setConnectTimeout(6 * 1000);
// 配置本地连接的content-type
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置浏览器编码
conn.setRequestProperty("Charset", "UTF-8");
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
// 将请求参数数据发送到服务器
dos.writeBytes(data);
dos.flush();
dos.close();
if (200 == conn.getResponseCode()) {
// 获得服务器的输出流
return conn.getInputStream();
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
// 获取网络数据
public static InputStream getInputStreamByGet(String urlPath) {
try {
URL url;
InputStream stream = null;
url = new URL(urlPath);
// 打开连接
HttpURLConnection conn;
conn = (HttpURLConnection) url.openConnection();
// 设置提交方式
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
// post方式不能使用缓存
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(true);
// 设置连接超时,
conn.setConnectTimeout(6 * 1000);
// 配置本地连接的content-type
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// 维持长连接
conn.setRequestProperty("Connection", "Keep-Alive");
// 设置浏览器编码
conn.setRequestProperty("Charset", "UTF-8");
if (200 == conn.getResponseCode()) {
// 获得服务器的输出流
stream = conn.getInputStream();
return stream;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//将流转换成字符串数据
public static String InputStreamToString(InputStream in) {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int count = -1;
try {
while ((count = in.read(data, 0, 1024)) != -1) {
outStream.write(data, 0, count);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
data = null;
try {
return new String(outStream.toByteArray(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}