Http:
1从网络获取数据
a从网络获取图片,以byte[]字节数组保存,并构建一个Bitmap
b.从网络获取为xml/Json,要解析,并封装成对象。
public byte[] getNetImage(String path) throws IOException{
URL url = new URL(path);
HttpURLConnection connection =(HttpURLConnection) url.openConnection();//基于HTTP协议连接对象
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStream in =connection.getInputStream();
return Utils.readStream(in);
}
return null;
}
//将流读取到字节数组
public static byte[] readStream(InputStream in) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
return baos.toByteArray();
}
2 以GET/POST方式上传到服务器
a.通过HTTP发送参数到服务器
GET不适合传输大数据
组拼url路径后的参数
POST:Content-Type Content-Length
组拼将要发送的实体数据
HttpClient开源项目
使用UrlEncodedFormEntity类构造实体数据
内部做了很多封装,性能不如手写的GET/POST
操作HTTPS,Cookie编码简单些
// 发送POST请求
public static boolean sendPostRequest(String path, Map<String, String> params, String encoding)throws IOException {
StringBuilder builder = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.append("?").append(entry.getKey()).append("=").append(entry.getValue()).append("&");
}
builder.deleteCharAt(builder.length() - 1);
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("POST");
connection.addRequestProperty("Content-Type", "");
connection.addRequestProperty("Content-Length", String.valueOf(builder.length()));
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(builder.toString().getBytes());// 只有取得服务器响应消息,才真正发送除数据,现在仅放到内存
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
return true;
}
return false;
}
// HttpClient
public static boolean sendHttpClientRequest(String path, Map<String, String> params,String encoding) throws IOException {
List<NameValuePair> valuePairs = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
valuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(valuePairs, encoding);// 构造实体数据
HttpPost post = new HttpPost(path);// 构造POST请求
post.setEntity(entity);
DefaultHttpClient client = new DefaultHttpClient();// 构造一个浏览器
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
return true;
}
return false;
}
b.通过Socket上传文件到服务器
先判断文件是否存在
HttpClient内部使用缓存,当上传文件超过1M,产生内存溢出Socket
实体数据长度= 文本类型长度+文件类型长度