Java 如何使用 HTTP-GET 连接输入用户名和密码访问 API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21967433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use HTTP-GET connect with input username and password for access API
提问by Flyzy Dev
I use API for connect information but I can't to get data from this API because I don' know How to use HTTP get connect with input username and password for access this data.
我使用 API 获取连接信息,但我无法从此 API 获取数据,因为我不知道如何使用 HTTP 获取连接并输入用户名和密码来访问此数据。
Main
主要的
String url = "http://flightxml.flightaware.com/json/FlightXML2/";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
TextView txt1 = (TextView)findViewById(R.id.textView1);
String result = HttpGet(url);
txt1.setText(result);
}
// Connect Http Get //
public String HttpGet(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString(); }}
In browser I can input username and password but in Android App I don't know How to input. same this pic.
在浏览器中我可以输入用户名和密码,但在 Android 应用程序中我不知道如何输入。同这张图。
采纳答案by Brian
Assuming your target API requires Basic Authentication, you need to add the credentials to the request as follows:
假设您的目标 API 需要基本身份验证,您需要将凭据添加到请求中,如下所示:
String user = "username";
String pwd = "password";
httpGet.addHeader("Authorization", "Basic " + Base64.encodeToString((user + ":" + pwd).getBytes(), Base64.NO_WRAP));
回答by Rocco Lucia
Try passing your credentials to the HTTP client setting your credential provider, specifying you want to use them just for that server:
尝试将您的凭据传递给设置凭据提供程序的 HTTP 客户端,指定您只想将它们用于该服务器:
String url = "http://flightxml.flightaware.com/json/FlightXML2/";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
TextView txt1 = (TextView)findViewById(R.id.textView1);
String result = HttpGet(url);
txt1.setText(result);
}
// Connect Http Get //
public String HttpGet(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
// Set up the credential provider for that server and port
CredentialsProvider credentials = new BasicCredentialsProvider();
credProvider.setCredentials(new AuthScope("flightxml.flightaware.com", 80),
new UsernamePasswordCredentials("username", "password"));
// and tell your client to use it
client.setCredentialsProvider(credentials);
// then fetch your data
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString(); }}
回答by Kevin Furmanski
Just a tip, use AsyncTask
instead of deactivating StrictMode.
只是一个提示,使用AsyncTask
而不是停用 StrictMode。