gpt4 book ai didi

java - 如何使用HTTP-GET连接输入用户名和密码访问API

转载 作者:太空宇宙 更新时间:2023-11-03 13:24:52 26 4
gpt4 key购买 nike

我使用 API 获取连接信息,但我无法从此 API 获取数据,因为我不知道如何使用 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();
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(); }}

在浏览器中我可以输入用户名和密码,但在 Android 应用程序中我不知道如何输入。与此图片相同。

http://i.stack.imgur.com/63EBI.jpg

最佳答案

假设您的目标 API 需要基本身份验证,您需要将凭据添加到请求中,如下所示:

String user = "username";
String pwd = "password";
httpGet.addHeader("Authorization", "Basic " + Base64.encodeToString((user + ":" + pwd).getBytes(), Base64.NO_WRAP));

关于java - 如何使用HTTP-GET连接输入用户名和密码访问API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com