HTTP通过基本身份验证获取Android [英] HTTP Get Android with Basic Auth
本文介绍了HTTP通过基本身份验证获取Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是REST服务的新手,我正在网上寻找几个小时...
I'm new to REST services and I'm looking for a few hours around the web...
我有一个REST服务网址,可以返回 JSON数据. 登录名(用户名和密码)为基本身份验证. 我正在寻找一个简单的库/代码段,该代码段可让我插入uri,用户名&密码,然后将JSON字符串还给我.
I have a REST service url that gives me back JSON data. The login (username & password) are basic auth. I'm looking for a simple library/code snippet that lets me insert the uri, username & password and give me back the JSON string.
任何帮助将不胜感激!
推荐答案
也许您可以尝试以下方法:
Maybe you can try something like this:
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的信息,请查看以下代码片段:
As for writing a JSONObject, check out this code snippet:
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);
}
这篇关于HTTP通过基本身份验证获取Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文