java如何使用HTTPGET connect为access API输入用户名和密码
我使用API获取连接信息,但无法从该API获取数据,因为我不知道如何使用HTTP get connect和输入用户名和密码来访问此数据
主要
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应用程序中我不知道如何输入。这张照片也一样
# 1 楼答案
假设您的目标API需要基本身份验证,则需要按如下方式向请求中添加凭据:
# 2 楼答案
提示一下,使用
AsyncTask
而不是停用StrictMode# 3 楼答案
尝试将凭据传递给HTTP客户端设置credential provider,指定要使用它们just for that server: