使用身份验证的HttpGet呼叫

时间:2018-10-20 14:36:57

标签: java android http

我是android和java开发的新手。我正在尝试向API(提供用户名和密码)发出GET请求,并将结果显示在日志中。

这是我到目前为止的工作:

package com.example.android.d1;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String username = "xxxx";
        String password = "xxxxxxxx";
        String hostname = "xxxxx.service-now.com";

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(new AuthScope(new HttpHost(hostname)), credentials);
        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCredentialsProvider(provider)
                .build();

        String query = "https://xxxxx.service-now.com/api/now/table/incident?sysparm_limit=1";

        try {
            HttpGet httpget = new HttpGet(query);
            httpget.setHeader("Accept", "application/json");
            System.out.println("Executing request " + httpget.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpget);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println(responseBody);
            }
            finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }
}

此代码从文档here中引用。

这是build.gradle文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.android.d1"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation files('libs/commons-cli-1.2.jar')
    implementation files('libs/commons-codec-1.10.jar')
    implementation files('libs/commons-logging-1.2.jar')
    implementation files('libs/fluent-hc-4.5.6.jar')
    implementation files('libs/httpclient-4.5.6.jar')
    implementation files('libs/httpclient-cache-4.5.6.jar')
    implementation files('libs/httpclient-win-4.5.6.jar')
    implementation files('libs/httpcore-4.4.10.jar')
    implementation files('libs/httpcore-ab-4.4.10.jar')
    implementation files('libs/httpcore-nio-4.4.10.jar')
    implementation files('libs/httpmime-4.5.6.jar')
    implementation files('libs/jna-4.4.0.jar')
    implementation files('libs/jna-platform-4.4.0.jar')
}

我遇到诸如error: unreported exception IOException; must be caught or declared to be thrown之类的编译错误。

有人可以帮助处理这种情况吗?还有什么方法可以更好地发出这样的GET请求。

1 个答案:

答案 0 :(得分:0)

看着您的代码,我才意识到这是一个Java应用程序的代码,不适合Android应用程序。

您可以尝试this(Android official documentation)this(recommended)

无论如何,回答问题:: 将此代码替换为

try {
        HttpGet httpget = new HttpGet(query);
        httpget.setHeader("Accept", "application/json");
        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
        }catch(Exception e){   //Not really necessary
            e.printStackTrace();  //Prints the exception in the logs
        }
        finally {
            response.close();
        }
    }catch(IOException e){  
        e.printStackTrace();
     }
     finally {
        httpclient.close();
    }

您需要捕获代码抛出的异常。 叫做ExceptionHandling

您看到,您正在尝试发出Http网络请求,并且“网络请求”可能会引发错误。因此,为了安全起见,我们应该捕获异常。

别忘了导入您的IOException

import java.io.IOException;