Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
android URLConnection和getInputStream出现错误401_Android_Json_Ssl_Get_Httprequest - Fatal编程技术网

android URLConnection和getInputStream出现错误401

android URLConnection和getInputStream出现错误401,android,json,ssl,get,httprequest,Android,Json,Ssl,Get,Httprequest,我需要通过GET方法发送代码,并在授权头中为我的服务器发送令牌。此代码返回“401未经授权”错误: 我错过了什么 class VerifyTask extends AsyncTask<String, String, String> { String Code; VerifyTask(String Code) { this.Code = Code; } @Override protected String doInBackg

我需要通过GET方法发送代码,并在授权头中为我的服务器发送令牌。此代码返回“401未经授权”错误:

我错过了什么

class VerifyTask extends AsyncTask<String, String, String> {
    String Code;

    VerifyTask(String Code) { 
        this.Code = Code;
    }

    @Override
    protected String doInBackground(String... params) {
        String response = null;
        BufferedReader reader = null;
            try {
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                    @Override
                    public void checkClientTrusted(
                               java.security.cert.X509Certificate[] chain,
                               String authType) throws CertificateException {
                          // TODO Auto-generated method stub

                   }

                    @Override
                    public void checkServerTrusted(
                               java.security.cert.X509Certificate[] chain,
                               String authType) throws CertificateException {
                          // TODO Auto-generated method stub

                   }

                    @Override
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                          // TODO Auto-generated method stub
                          return null ;
                   }

                } };
                   // Install the all-trusting trust manager
                   final SSLContext sslContext = SSLContext.getInstance("SSL");
                  sslContext.init( null, trustAllCerts,
                               new java.security.SecureRandom());
                   // Create an ssl socket factory with our all-trusting manager
                   final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext
                              .getSocketFactory();


                   final URLConnection connection = (HttpsURLConnection) new URL("https://myserver.com/api/v1/verify?code=" + Code).openConnection();
                   ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
                   ((HttpsURLConnection) connection).setRequestMethod("GET");
                   ((HttpsURLConnection) connection).setRequestProperty("Authorization", token);
                   ((HttpsURLConnection) connection).setRequestProperty("Connection", "Keep-Alive");
                   ((HttpsURLConnection) connection).setRequestProperty("Accept", "application/json, */*");                    
                   ((HttpsURLConnection) connection).setUseCaches(false);

                   try{

                       reader = new BufferedReader(new InputStreamReader(
                              ((HttpsURLConnection) connection).getInputStream()));
                       StringBuffer sb = new StringBuffer("");
                       String line = "";
                       while ((line = reader.readLine()) != null) {
                         sb.append(line).append("\n");
                       }
                        //view data
                        response = sb.toString();
                        System.out.println("RESP=" + response);
                   } catch (IOException e) {
                        int responsecode = ((HttpURLConnection) connection).getResponseCode();
                        System.out.println("SERVERERR=" + String.valueOf(responsecode) + ": "+((HttpURLConnection) connection).getResponseMessage());
                   }

            } catch (Exception e) {
                    System.out.println("Exp=" + e);
            }
            return null;
    }

    @Override
    protected void onPostExecute(String result) {

        //dialog.dismiss();
        super.onPostExecute(result);

    }

    @Override
    protected void onPreExecute() {

        //dialog.setMessage("Loading...");
        //dialog.setIndeterminate(true);
        //dialog.setCancelable(true);
        //dialog.show();
        super.onPreExecute();

    }
}
    $.ajax({
    url: 'https://myserver.com/api/v1/verify?code='+Code,
    data: "",
    dataType: 'json',
    type: 'GET',
    async: true,
    processData: false,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Authorization", token);
    },
    cache: false,
    success: function (data) {
        //do something with data
    },
    error: function (jqXHR, exception, textStatus, errorThrow) {
        if (jqXHR.status === 0) {
            resp='Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            resp='Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            resp='Error [500].';
        } else if (jqXHR.status == 401) {
            resp='Auth ERROR';          
        } else if (exception === 'parsererror') {
            resp='Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            resp='Time out error.';
        } else if (exception === 'abort') {
            resp='Ajax request aborted.';
        } else {
            resp='Uncaught Error.\n' + errorThrow;
        }
    },
    crossDomain: true
  });