gpt4 book ai didi

android - HTTP 使用基本身份验证获取 Android

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

我是 REST 服务的新手,我正在网上找几个小时......

我有一个 REST 服务 url,可以返回 JSON 数据。登录名(用户名和密码)是基本身份验证。我正在寻找一个简单的库/代码 fragment ,它可以让我插入 uri、用户名和密码并返回 JSON 字符串。

如有任何帮助,我们将不胜感激!

最佳答案

也许你可以尝试这样的事情:

StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("YOUR WEBSITE HERE");

// Add authorization header
httpGet.addHeader(BasicScheme.authenticate( new UsernamePasswordCredentials("user", "password"), "UTF-8", false));

// Set up the header types needed to properly transfer JSON
httpGet.setHeader("Content-Type", "application/json");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
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(ParseJSON.class.toString(), "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

关于编写 JSONObject,请查看以下代码 fragment :

public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "Jack Hack");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Hacker");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}

关于android - HTTP 使用基本身份验证获取 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26176591/

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