GVKun编程网logo

android的volley学习(android volatile)

17

在本文中,我们将详细介绍android的volley学习的各个方面,并为您提供关于androidvolatile的相关解答,同时,我们也将为您带来关于AndroidKotlin-VolleyMulti

在本文中,我们将详细介绍android的volley学习的各个方面,并为您提供关于android volatile的相关解答,同时,我们也将为您带来关于Android Kotlin - Volley Multipart 请求 VolleyFileUploadRequest JSONObject 响应、android Volley、android volley https、android Volley Post 请求失败的有用知识。

本文目录一览:

android的volley学习(android volatile)

android的volley学习(android volatile)

更简单的一种方式是在build.gradle中引入依赖【推荐这种方式】

compile 'com.android.volley:volley:1.1.1'

StringRequest的用法
接下来我们看看如何发起一条HTTP请求,然后接收HTTP响应。首先需要获取到一个RequestQueue对象,可以调用如下方法获取到:

RequestQueue mQueue = Volley.newRequestQueue(context);
首先创建一个StringRequest实例,构造函数中三个参数分别为:http请求方式:Get/Post,请求url,请求成功监听器(Response.Listener),请求错误监听器(Response.ErrorListener)。然后将request对象设置好Tag标记(方便以后针对性的取消请求),将request放入请求队列中

注意这里拿到的RequestQueue是一个请求队列对象,它可以缓存所有的HTTP请求,然后按照一定的算法并发地发出这些请求。RequestQueue内部的设计就是非常合适高并发的,因此我们不必为每一次HTTP请求都创建一个RequestQueue对象,这是非常浪费资源的,基本上在每一个需要和网络交互的Activity中创建一个RequestQueue对象就足够了

接下来为了要发出一条HTTP请求,我们还需要创建一个StringRequest对象,如下所示:

StringRequest stringRequest = new StringRequest("https://www.baidu.com",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("TAG", response);
}
}, new Response.ErrorListener() {
@Override
public void one rrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});

 

可以看到,这里new出了一个StringRequest对象,StringRequest的构造函数需要传入三个参数,第一个参数就是目标服务器的URL地址,第二个参数是服务器响应成功的回调,第三个参数是服务器响应失败的回调。其中,目标服务器地址我们填写的是百度的首页,然后在响应成功的回调里打印出服务器返回的内容,在响应失败的回调里打印出失败的详细信息。

最后,将这个StringRequest对象添加到RequestQueue里面就可以了,如下所示:

mQueue.add(stringRequest);

AndroidManifest.xml中添加如下权限:

<uses-permission android:name="android.permission.INTERNET" />

原文链接:https://blog.csdn.net/u010356768/article/details/87720280

首先创建一个StringRequest实例,构造函数中三个参数分别为:http请求方式:Get/Post,请求url,请求成功监听器(Response.Listener),请求错误监听器(Response.ErrorListener)。然后将request对象设置好Tag标记(方便以后针对性的取消请求),将request放入请求队列中。

Get请求方式:

 

Android Kotlin - Volley Multipart 请求 VolleyFileUploadRequest JSONObject 响应

Android Kotlin - Volley Multipart 请求 VolleyFileUploadRequest JSONObject 响应

这是怎么做的:

val response = JSONObject(String(it.data))

android Volley

android Volley

现在让我选择我会选retrofit2.0:https://github.com/AnyLifeZLB/Retrofit2.0_Demo

 

http://www.cnblogs.com/angeldevil/p/3735051.html

http://www.codekk.com/blogs/detail/54cfab086c4761e5001b2542

 

https://bxbxbai.github.io/2014/09/14/android-working-with-volley/

下面是序列教程的第一篇:

http://blog.csdn.net/guolin_blog/article/details/17482095

 

 

android volley https

android volley https

Android中使用volley进行Https 通讯的时候,如果没有申请正式会报错:( 我们的服务器用nginx作为容器 )

VolleyEror: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

最好的办法是按照规则来办事:加证书。然而调试服务器说不加...

那么要怎么才不会报错呢?

1.查看接口 X509TrustManger.java ( 在包javax.net.ssl )

X509TrustManager.Java
//------------------------------------

package javax.net.ssl;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * The trust manager for X509 certificates to be used to perform authentication
 * for secure sockets.
 */
public interface X509TrustManager extends TrustManager {

    /**
     * Checks whether the specified certificate chain (partial or complete) can
     * be validated and is trusted for client authentication for the specified
     * authentication type.
     *
     * @param chain
     *            the certificate chain to validate.
     * @param authType
     *            the authentication type used.
     * @throws CertificateException
     *             if the certificate chain can''t be validated or isn''t trusted.
     * @throws IllegalArgumentException
     *             if the specified certificate chain is empty or {@code null},
     *             or if the specified authentication type is {@code null} or an
     *             empty string.
     */
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException;


    /**
     * Checks whether the specified certificate chain (partial or complete) can
     * be validated and is trusted for server authentication for the specified
     * key exchange algorithm.
     *
     * @param chain
     *            the certificate chain to validate.
     * @param authType
     *            the key exchange algorithm name.
     * @throws CertificateException
     *             if the certificate chain can''t be validated or isn''t trusted.
     * @throws IllegalArgumentException
     *             if the specified certificate chain is empty or {@code null},
     *             or if the specified authentication type is {@code null} or an
     *             empty string.
     */
    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException;

    /**
     * Returns the list of certificate issuer authorities which are trusted for
     * authentication of peers.
     *
     * @return the list of certificate issuer authorities which are trusted for
     *         authentication of peers.
     */
    public X509Certificate[] getAcceptedIssuers();
}


//-------------------------------------------------------------------------------


2.FakeX509TrustManger  implements X509TrustManager

package com.http.utils;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
*
*
* Created by Administrator on 2016/2/17.
*/
public class FakeX509TrustManager 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 FakeX509TrustManager() };
       }

       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());
   }

}


3.在请求前设置忽略所有的验证,允许所有的SSL


FakeX509TrustManager.allowAllSSL(); //it is dangerous!但是有的时候我们需要这样做!!
      //========================StringRequest=====================================================
      StringRequest httpRequest = new StringRequest(requestMethod, url, new Response.Listener<String>() {
          @Override
          public void onResponse(String response) {

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。


参考链接:http://www.trinea.cn/android/android-java-https-ssl-exception-2/

android Volley Post 请求失败

android Volley Post 请求失败

JSONObject ClientKey = null;
            listMsg = getSmsInfo(listPhone);

            Toast.makeText(
                    getActivity(),
                    "listMsg.size()...................................................."
                            + listMsg.size(), Toast.LENGTH_SHORT).show();
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity()
                    .getApplicationContext());
            try {
                for (int i = 0; i < 1; i++) {
                    /* 封装子对象 */
                    ClientKey = new JSONObject();
                    ClientKey.put("sms__id", listMsg.get(i).getSms__id());
                    ClientKey.put("sms_thread_id", listMsg.get(i)
                            .getSms_thread_id());
                    ClientKey.put("sms_body", listMsg.get(i).getSms_body());
                    ClientKey.put("sms_address", listMsg.get(i)
                            .getSms_address());
                    ClientKey.put("sms_person", listMsg.get(i).getSms_person());
                    ClientKey.put("sms_body", listMsg.get(i).getSms_body());
                    ClientKey.put("sms_status", listMsg.get(i).getSms_status());
                    ClientKey.put("sms_date", listMsg.get(i).getSms_date());
                    ClientKey.put("sms_type", listMsg.get(i).getSms_type());
                    ClientKey.put("sms_protocol", listMsg.get(i)
                            .getSms_protocol());
                    ClientKey.put("sms_read", listMsg.get(i).getSms_read());
                    ClientKey.put("sms_service_center", listMsg.get(i)
                            .getSms_service_center());
                    jsonRequest = new JsonObjectRequest(Method.POST,
                            AllFinalInfo.SERVER_URL, ClientKey,
                            new Response.Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    Toast.makeText(
                                            getActivity(),
                                            "response.toString().....................................",
                                            Toast.LENGTH_SHORT).show();
                                }
                            }, new Response.ErrorListener() {

                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    error.printStackTrace();
                                    Toast.makeText(
                                            getActivity(),
                                            "error.getMessage().....................................",
                                            Toast.LENGTH_SHORT).show();
                                    error.printStackTrace();
                                }
                            });

                    requestQueue.add(jsonRequest);
                }
            } catch (Exception e) {
            }


路径和数据都正确,但是每次都执行new Response.ErrorListener() {}这个方法,不知道为什么?????

关于android的volley学习android volatile的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于Android Kotlin - Volley Multipart 请求 VolleyFileUploadRequest JSONObject 响应、android Volley、android volley https、android Volley Post 请求失败的相关信息,请在本站寻找。

本文标签: