Android 401 Unauthorized HttpURLConnection with Basic Auth

时间:2015-08-11 05:23:48

标签: android httpurlconnection basic-authentication intentservice unauthorized

我正在尝试使用一些字符串参数和POST request发送jpeg image file。整个代码位于IntentService

我正在使用基本auth的授权标头(与其他网络服务一起使用时,凭据可以正常工作)。

我无法真正得到错误,也许是错误的请求属性。请记住,我正在发送字符串,但也是一个图像。

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

1 个答案:

答案 0 :(得分:0)

尝试使用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;
}