android6.0中把apache http client所有的包与类都标记为deprecated不再建议使用所有跟http相关的数据请求与提交操作都通过httpurlconnection类实现,现实是很多android开发者一直都apache http client来做andoird客户端与后台http接口数据交互,小编刚刚用httpurlconnection做了一个android的app,不小心踩到了几个坑,总结下最常用的就通过httpurlconnection来post提交json数据与get请求json数据。此外就是下载图片,下载图片分为显示进度与不显示进度两种。其中提交数据的时候涉及中文一定要先把中文转码成utf-8之后在post提交,否则就会一直遇到http 400的错误。
一、get请求json数据的例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public userdto execute(string... params) {
inputstream inputstream = null ;
httpurlconnection urlconnection = null ;
try {
// read responseurlencoder.encode(para, "gbk");
string urlwithparams = domain_address + member_request_token_url + "?username=" + java.net.urlencoder.encode(params[ 0 ], "utf-8" ) + "&password=" + params[ 1 ];
url url = new url(urlwithparams);
urlconnection = (httpurlconnection) url.openconnection();
/* optional request header */
urlconnection.setrequestproperty("content-type", "application/json; charset=utf-8");
/* optional request header */
urlconnection.setrequestproperty("accept", "application/json");
/* for get request */
urlconnection.setrequestmethod("get");
int statuscode = urlconnection.getresponsecode();
/* 200 represents http ok */
if (statuscode == 200 ) {
inputstream = new bufferedinputstream(urlconnection.getinputstream());
string response = httputil.convertinputstreamtostring(inputstream);
gson gson = new gson();
userdto dto = gson.fromjson(response, userdto. class );
if (dto != null && dto.gettoken() != null ) {
log.i( "token" , "find the token = " + dto.gettoken());
}
return dto;
}
} catch (exception e) {
e.printstacktrace();
} finally {
if (inputstream != null ) {
try {
inputstream.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
if (urlconnection != null ) {
urlconnection.disconnect();
}
}
return null ;
}
|
二、post提交json数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
public map<string, string> execute(notificationdto dto) {
inputstream inputstream = null ;
httpurlconnection urlconnection = null ;
try {
url url = new url(geturl);
urlconnection = (httpurlconnection) url.openconnection();
/* optional request header */
urlconnection.setrequestproperty("content-type", "application/json; charset=utf-8");
/* optional request header */
urlconnection.setrequestproperty("accept", "application/json");
dto.setcreator(java.net.urlencoder.encode(dto.getcreator(), "utf-8"));
// read response
/* for get request */
urlconnection.setrequestmethod( "post" );
urlconnection.setdooutput( true );
dataoutputstream wr = new dataoutputstream(urlconnection.getoutputstream());
gson gson = new gson();
string jsonstring = gson.tojson(dto);
wr.writebytes(jsonstring);
wr.flush();
wr.close();
// try to get response
int statuscode = urlconnection.getresponsecode();
if (statuscode == 200 ) {
inputstream = new bufferedinputstream(urlconnection.getinputstream());
string response = httputil.convertinputstreamtostring(inputstream);
map<string, string> resultmap = gson.fromjson(response, map. class );
if (resultmap != null && resultmap.size() > 0 ) {
log.i( "applydesigner" , "please check the map with key" );
}
return resultmap;
}
}
catch (exception e)
{
e.printstacktrace();
}
finally
{
if (inputstream != null ) {
try {
inputstream.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
if (urlconnection != null ) {
urlconnection.disconnect();
}
}
return null ;
}
|
三、下载图片显示下载进度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
package com.example.demo;
import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.net.httpurlconnection;
import java.net.url;
import android.graphics.bitmap;
import android.graphics.bitmapfactory;
import android.os.asynctask;
import android.os.handler;
import android.os.message;
import android.util.log;
public class imageloadtask extends asynctask<string, void , bitmap> {
private handler handler;
public imageloadtask(handler handler) {
this .handler = handler;
}
protected void onpostexecute(bitmap result) {
message msg = new message();
msg.obj = result;
handler.sendmessage(msg);
}
protected bitmap doinbackground(string... geturls) {
inputstream inputstream = null ;
httpurlconnection urlconnection = null ;
try {
// open connection
url url = new url(geturls[ 0 ]);
urlconnection = (httpurlconnection) url.openconnection();
/* for get request */
urlconnection.setrequestmethod( "get" );
int filelength = urlconnection.getcontentlength();
int statuscode = urlconnection.getresponsecode();
if (statuscode == 200 ) {
inputstream = urlconnection.getinputstream();
byte data[] = new byte [ 4096 ];
long total = 0 ;
int count;
bytearrayoutputstream output = new bytearrayoutputstream();
while ((count = inputstream.read(data)) != - 1 ) {
total += count;
// publishing the progress....
if (filelength > 0 && handler != null ) {
handler.sendemptymessage((( int ) (total * 100 / filelength)) - 1 );
}
output.write(data, 0 , count);
}
bytearrayinputstream bufferinput = new bytearrayinputstream(output.tobytearray());
bitmap bitmap = bitmapfactory.decodestream(bufferinput);
inputstream.close();
bufferinput.close();
output.close();
log.i( "image" , "already get the image by uuid : " + geturls[ 0 ]);
handler.sendemptymessage( 100 );
return bitmap;
}
} catch (exception e) {
e.printstacktrace();
} finally {
if (inputstream != null ) {
try {
inputstream.close();
} catch (ioexception e) {
e.printstacktrace();
}
}
if (urlconnection != null ) {
urlconnection.disconnect();
}
}
return null ;
}
}
|
总结:使用httpurlconnection提交json数据的时候编码方式为utf-8所有中文字符请一定要预先转码为utf-8,然后在后台服务器对应的api中解码为utf-8,不然就会报错http 400。
以上就是本文的全部内容,希望对大家的学习android软件编程有所帮助。