Tom*_*mCB 3 android basic-authentication
我是REST服务的新手,我正在网上寻找几个小时......
我有一个REST服务URL,它可以返回JSON数据.登录(用户名和密码)是基本身份验证.我正在寻找一个简单的库/代码片段,让我插入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();
}
Run Code Online (Sandbox Code Playgroud)
至于编写JSONObject,请查看以下代码片段:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8396 次 |
| 最近记录: |