1 Volley发送get请求:
[java] view plaincopy
- public void getJson() {
- String url = "http://"+host+":8080/web/json.jsp?username=xjs&password=123456";
- mQueue.add(new JsonObjectRequest(Method.GET, url, null,
- new Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- Log.e(TAG, "response : " + response.toString());
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- String err = error.getMessage();
- Log.e(TAG, "err : " + err);
- }
- }));
- }
2 Volley发送post请求:
[java] view plaincopy
- public void postJson() {
- String url = "http://"+host+":8080/web/json.jsp";
- StringRequest postRequest = new StringRequest(
- Request.Method.POST,
- url,
- new Response.Listener<String>() {
- @Override
- public void onResponse(String response) {
- // response
- Log.d("Response", response);
- }
- }, new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- // error
- Log.d("Error.Response", error.getMessage());
- }
- }) {
- @Override
- protected Map<String, String> getParams() {
- Map<String, String> params = new HashMap<String, String>();
- params.put("username", "xjs");
- params.put("password", "123456");
- return params;
- }
- };
- mQueue.add(postRequest);
- }
3 Volley获取网络图片:
[java] view plaincopy
- public void getImage() {
- String imageUrl = "http://"+host+":8080/web/image.jsp";
- NetworkImageView view = (NetworkImageView) findViewById(R.id.network_image_view);
- view.setDefaultImageResId(android.R.drawable.ic_menu_rotate);
- view.setErrorImageResId(android.R.drawable.ic_delete);
- view.setImageUrl(imageUrl, new ImageLoader(mQueue, new BitmapLruCache(1024 * 4)));
- }
4 Volley发送Https请求,需要修改源码:
[java] view plaincopy
- protected HttpURLConnection createConnection(URL url) throws IOException {
- if (url.toString().toLowerCase(Locale.CHINA).startsWith("https")) {
- HTTPSTrustManager.allowAllSSL();
- }
- return (HttpURLConnection) url.openConnection();
- }
- //HTTPSTrustManager.java:
- public class HTTPSTrustManager implements X509TrustManager {
- private static TrustManager[] trustManagers;
- private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};
- @Override
- public void checkClientTrusted(
- java.security.cert.X509Certificate[] x509Certificates, String s)
- throws java.security.cert.CertificateException {
- // To change body of implemented methods use File | Settings | File
- // Templates.
- }
- @Override
- public void checkServerTrusted(
- java.security.cert.X509Certificate[] x509Certificates, String s)
- throws java.security.cert.CertificateException {
- // To change body of implemented methods use File | Settings | File
- // Templates.
- }
- public boolean isClientTrusted(X509Certificate[] chain) {
- return true;
- }
- public boolean isServerTrusted(X509Certificate[] chain) {
- return true;
- }
- @Override
- public X509Certificate[] getAcceptedIssuers() {
- return _AcceptedIssuers;
- }
- public static void allowAllSSL() {
- HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
- @Override
- public boolean verify(String arg0, SSLSession arg1) {
- // TODO Auto-generated method stub
- return true;
- }
- });
- SSLContext context = null;
- if (trustManagers == null) {
- trustManagers = new TrustManager[] { new HTTPSTrustManager() };
- }
- try {
- context = SSLContext.getInstance("TLS");
- context.init(null, trustManagers, new SecureRandom());
- } catch (NoSuchAlgorithmException e) {
- e.printStackTrace();
- } catch (KeyManagementException e) {
- e.printStackTrace();
- }
- HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
- }
- }
5 Volley获取服务端返回的cookie,需要修改源码:
[java] view plaincopy
- @Override
- public HttpResponse performRequest(Request<?> request,Map<String, String> additionalHeaders)
- throws IOException,AuthFailureError {
- for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
- if (header.getKey() != null) {
- String key = header.getKey();
- List<String> values = header.getValue();
- if(key.equalsIgnoreCase("set-cookie")){
- StringBuilder cookieString = new StringBuilder();
- for(String value : values){
- cookieString.append(value).append("\n");//用\n作为分隔符,cookie中不应该有回车符号
- }
- cookieString.deleteCharAt(cookieString.length() - 1);
- Header h = new BasicHeader(header.getKey(), cookieString.toString());
- response.addHeader(h);
- }else{
- Header h = new BasicHeader(header.getKey(), values.get(0));
- response.addHeader(h);
- }
- }
- }
- }
- //然后再request中重写parseNetworkResponse():
- @Override
- protected Response<String> parseNetworkResponse(NetworkResponse response) {
- Response<String> superResponse = super.parseNetworkResponse(response);
- Map<String, String> responseHeaders = response.headers;
- String rawCookies = responseHeaders.get("Set-Cookie");
- //服务端返回是 set-cookie:JSESSIONID=D90B58454550B4D37C4B66A76BF27B93; Path=/otn BIGipServerotn=2564030730.64545.0000; path=/
- String part1 = substring(rawCookies, "", ";");
- String part2 = substring(rawCookies, "\n", ";");
- //客户端需要的是 cookie:JSESSIONID=D90B58454550B4D37C4B66A76BF27B93; BIGipServerotn=2564030730.64545.0000;
- cookies = part1 + "; " + part2 + ";";
- return superResponse;
- }
6 Volley发请求的时候上传cookie,在request中重写getHeaders():
[java] view plaincopy
- @Override
- public Map<String, String>getHeaders() throws AuthFailureError {
- if(cookies!= null && cookies.length() > 0){
- HashMap<String,String> headers = newHashMap<String, String>();
- headers.put("Cookie",cookies);
- returnheaders;
- }
- returnsuper.getHeaders();
- }
7 Volley自定义request:
[java] view plaincopy
- public class ByteArrayRequest extends Request<byte[]>{
- private final Listener<byte[]> mListener;
- public ByteArrayRequest(int method, String url, Listener<byte[]> listener, ErrorListener errlistener) {
- super(method, url, errlistener);
- mListener = listener;
- }
- @Override
- protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
- if(response == null){
- return null;
- }
- if(response.statusCode != HttpStatus.SC_OK){
- return null;
- }
- byte[] bytes = response.data;
- return Response.success(bytes, null);
- }
- @Override
- protected void deliverResponse(byte[] response) {
- if(mListener != null){
- mListener.onResponse(response);
- }
- }
- }
8 Volley设置请求超时时间:
[java] view plaincopy
- @Override
- public RetryPolicy getRetryPolicy() {
- RetryPolicyretryPolicy = new DefaultRetryPolicy(5000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
- returnretryPolicy;
- }
如果是用这种方式上传post参数:
[java] view plaincopy
- public void postJson() {
- String url = "http://"+host+":8080/web/json.jsp";
- HashMap<String, String> params = new HashMap<String, String>();
- params.put("username", "xjs");
- params.put("password", "123456");
- JsonObjectRequest postRequest = new JsonObjectRequest(
- Request.Method.POST,
- url,
- new JSONObject(params),
- new Response.Listener<JSONObject>() {
- @Override
- public void onResponse(JSONObject response) {
- Log.e(TAG, "response : " + response.toString());
- }
- },
- new Response.ErrorListener() {
- @Override
- public void onErrorResponse(VolleyError error) {
- Log.e("Error: ", error.getMessage());
- }
- });
- mQueue.add(postRequest);
- }
要注意,上传的参数并不是按照key-value拼接起来放在body中上传的,而是按照json的形式上传的,因此,服务端用request.getParameter("key")这种形式是无法取出来value的,只能是request.getInputStream(),然后把整个的body还原出原来的json串,然后从json中再取值。
时间: 2024-11-09 20:12:43