【问题标题】:Android 401 Unauthorized HttpURLConnection with Basic Auth带有基本身份验证的 Android 401 未经授权的 HttpURLConnection
【发布时间】:2015-08-11 05:23:47
【问题描述】:

我正在尝试发送带有一些字符串参数的POST requestjpeg image file。整个代码在IntentService

我正在为基本auth 使用 Authorization 标头(凭据在将它们与其他 Web 服务一起使用时有效)。

我真的不知道出了什么问题,也许是请求属性有问题。请记住,我正在发送字符串,但也发送图像。

    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;

    try {
        FileInputStream fileInputStream = new FileInputStream(new File(filePath));

        URL url = new URL(urlServer);
        String credentials = "test@test.com"+":"+"testtest";

        final String basicAuth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", basicAuth);
        connection.setRequestProperty("Content-Type", "multipart/form-data");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Connection", "Keep-Alive");

        connection.setInstanceFollowRedirects(false);

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");



        outputStream = new DataOutputStream(connection.getOutputStream());

        outputStream.writeBytes("imei="+ getImei()
                        + "&id=38"
                        + "&type = b"
                        + "&step=1"
                        + "&image="
        );

        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];

        int sentBytes = 0;
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            mBuilder.setProgress(100,(int) (sentBytes * 100 / bytesAvailable),false);
            mNotifyManager.notify(1, mBuilder.build());
            outputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            sentBytes += bufferSize;
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        mBuilder.setContentText("Upload complete");
        mBuilder.setProgress(0, 0, false);
        mNotifyManager.notify(1, mBuilder.build());

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        if(connection.getResponseCode() == HttpURLConnection.HTTP_MOVED_TEMP){
            url = new URL(connection.getHeaderField("Location"));
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestProperty("Authorization", basicAuth);
        }

        InputStreamReader isr = null;
        BufferedReader reader = null;
        StringBuilder sb = new StringBuilder();

        String line = "";
        isr = new InputStreamReader(
                connection.getInputStream());
        reader = new BufferedReader(isr);
        line = reader.readLine();
        while (line != null) {
            sb.append(line);
            try {
                line = reader.readLine();
            }catch (Exception e){
                line = null;
            }
        }
        String a;
        a = sb.toString();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

【问题讨论】:

  • 尝试使用 DefaultHttpClient
  • 401 错误不一定是因为您发送的用户名或密码错误。也可能是因为编码错误。

标签: android httpurlconnection basic-authentication intentservice unauthorized


【解决方案1】:

尝试使用 DefaultHttpClient 如下。代替 Base64.encodeToString,尝试如下 UsernamePasswordCredentials。即使我使用带有基本身份验证的 POST 方法,它也有效。

private HttpResponse getWebServiceResponse(String URL, ArrayList <NameValuePair> params)
    {
        HttpResponse httpResponse = null;
        try 
        {

            HttpParams httpParameters = new BasicHttpParams();
            // Set httpParameters  like timeout etc. here.

// defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            httpClient.getCredentialsProvider().setCredentials(
                    AuthScope.ANY, new UsernamePasswordCredentials("USERNAME", "PASSWORD"));    
            HttpPost httpPost = new HttpPost(URL);
            try 
            {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            } catch (UnsupportedEncodingException e) {

            }
            httpResponse = httpClient.execute(httpPost);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       
        return httpResponse;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 2018-07-09
  • 2014-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
相关资源
最近更新 更多