post上传和压缩、插件模拟请求

时间:2022-12-01 11:47:07
 

gzip

gzip一种压缩方式,或者是文件形式,它主要用于网络传输数据的压缩

gzip压缩好不好用

  • 浏览器:网速一定.内容越小.请求响应的速度是不是更快
  • 手机server:返回数据类型是json/xml->文本-->压缩率会很高.

gzip执行流程

  • //1. 告知服务器.客户端支持gzip解压

    * get.addHeader("Accept-Encoding", "gzip");
  • //2. 根据响应头得知服务器知否进行了gzip压缩

    * Header[] headers = response.getHeaders("Content-Encoding");
    for (Header header : headers) {
    if ("gzip".equals(header.getValue())) {
    isUseGzip = true;
    }
    }
  • //3.根据是否使用gzip.解压具体的数据

    if (isUseGzip) {
    GZIPInputStream in = new GZIPInputStream(entity.getContent());
    result = IoUtils.convertStreamToString(in);
    } else {
    result = EntityUtils.toString(entity);
    }
  • 服务端具体怎么支持gzip压缩.根据使用的服务器语言来定

post请求参数的形式

  • key-value--->表单:结构比较单一.而且比较繁琐

    List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
    for (String key : parmas.keySet()) {
    BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, parmas.get(key));
    parameters.add(basicNameValuePair);
    }
    UrlEncodedFormEntity form = new UrlEncodedFormEntity(parameters);
    post.setEntity(form);
  • jsonString形式:结构灵活.实际开发用的很多

        post.setEntity(new StringEntity(jsonString));
  • file形式:需要jar包httpmime:很多框架上传图片就是用他

        MultipartEntity entity = new MultipartEntity();
    entity.addPart("actimg", new FileBody(file));
    post.setEntity(entity);
  • 多张图片上传:写个循环,用键值,可以用BasicNameValuePair,也可以用file,循环添加,也可以用base64变成string上传
  • Base64:byte[]-->string
    • 上传图片,语音:
    • 存对象到sp:如map
	iv = (ImageView) findViewById(R.id.iv);
findViewById(R.id.btn1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//1.bitmap
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
//2. bitmap-->byte[]
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteArray = baos.toByteArray();
//3.byte[]->string,这样就可以用string传给服务器
String bitmapString = Base64.encodeToString(byteArray, Base64.DEFAULT);
System.out.println("bitmapString :" + bitmapString);
//4. string-->byte[];
byte[] bitmapByteArr = Base64.decode(bitmapString, Base64.DEFAULT);
//5.byte[]-->bitmap
Bitmap bitmap2 = BitmapFactory.decodeByteArray(bitmapByteArr, 0, bitmapByteArr.length);
//6.在imageView上设置图片
iv.setImageBitmap(bitmap2);
//obj-->byte[] -->string->sp
}
});

  

post的content-type

  • application/x-www-form-urlencoded :表单类型-->key-value,默认
  • multipart/form-data :文件上传
  • application/json :jsonString
  • text/xml :xml
  • text/plain:文本
  • post.addHeader("Content-Type", "application/json");//如果后台固定死了.不加请求头.同样返回json那就没问题.但是如果后台逻辑和这个请求头有关系.就必须要加上.可以肯定的说.加了万无一失
 
 

MainActivity

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initGzip();
Map<String, String> map = new HashMap<String, String>();
map.put("name", "billy"); initPostKeyValue(map);
String jsonString = "{\"name\":\"billy\"}";
initPostJsonString(jsonString);
File file = new File("");
initPostFile(file);
}
/**
* 文件的上传
* @param file
*/
private void initPostFile(File file) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("");
//2. 传递二进制类型的参数
MultipartEntity entity = new MultipartEntity();
entity.addPart("actimg", new FileBody(file));
post.setEntity(entity);
httpClient.execute(post);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用jsonString post数据库
* @param jsonString
*/
private void initPostJsonString(String jsonString) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("");
post.addHeader("Content-Type", "application/json");
//Content-Type text/xml-->xml
//Content-Type application/json-->json
//2. 传递jsonString类型的参数
post.setEntity(new StringEntity(jsonString));
httpClient.execute(post);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 使用key-value的形式post数据
* @param parmas 请求参数对于的map集合
*/
private void initPostKeyValue(Map<String, String> parmas) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("");
//1. 传递key-value的参数
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
for (String key : parmas.keySet()) {
BasicNameValuePair basicNameValuePair = new BasicNameValuePair(key, parmas.get(key));
parameters.add(basicNameValuePair);
}
UrlEncodedFormEntity form = new UrlEncodedFormEntity(parameters);
post.setEntity(form);
httpClient.execute(post);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void initGzip() {
findViewById(R.id.btn1).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
try {
boolean isUseGzip = false;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet get = new HttpGet("http://httpbin.org/gzip");
//1. 告知服务器.客户端支持gzip解压
get.addHeader("Accept-Encoding", "gzip");
HttpResponse response = httpClient.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
//2. 根据响应头得知服务器知否进行了gzip压缩
Header[] headers = response.getHeaders("Content-Encoding");
for (Header header : headers) {
if ("gzip".equals(header.getValue())) {
isUseGzip = true;
}
}
HttpEntity entity = response.getEntity();
//3.根据是否使用gzip.解压具体的数据
String result = "";
if (isUseGzip) {
GZIPInputStream in = new GZIPInputStream(entity.getContent());
result = IoUtils.convertStreamToString(in);
} else {
result = EntityUtils.toString(entity);
}
System.out.println("result:" + result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
});
}
}

  

 

restclient(firfox插件),postman(谷歌浏览器)

网络请求模拟插件,post用,get直接在浏览器网页就打开了