使用Java for Android的HTTP API请求
我找到了我想免费玩的API。我想问一下是否要使用API开发Android应用,并且该API基于HTTP协议(RESTful),如何使用
对象来实现?
我有一般要求的信息。
HEAD /authenticate/ HTTP/1.1Host: my.api.com
Date: Thu, 17 Jul 2008 14:52:54 GMT
X-SE-Client: some-value
X-SE-Accept: xml
X-SE-Auth: 90a6d325e982f764f86a7e248edf6a660d4ee833
以上的回应将是成功的话。
HTTP/1.1 200 OKDate: Thu, 17 Jul 2008 14:52:55 GMT
Server: MyApi
Content-Length: 795
Connection: close
Content-Type: text/xml
我知道如何使用HTTPClient发送HTTP请求,但是否向请求中添加了额外的标头和其他不必要的内容?如何查看HTTPClient对象发出的请求?我只想简单地请求像
一样传递文本。
回答:
您应该能够在Android中使用HttpClient来完成所需的工作。我刚刚完成了将Android与ASP.NET MVC 3站点集成的第一部分,我必须说-
这非常轻松。我使用Json作为数据交换格式。
您可以在建立请求后通过设置调试点来准确查看标头的外观。这是一些示例代码(请记住,这只是示例代码-并非完整的实现)。
此类由不同于UI线程的单独线程调用:
public class RemoteDBAdapter { public String register(String email, String password) throws Exception
{
RestClient c = new RestClient("http://myurl/Account/Register");
c.AddHeader("Accept", "application/json");
c.AddHeader("Content-type", "application/json");
c.AddParam("Email", email);
c.AddParam("Password", password);
c.Execute(RequestMethod.POST);
JSONObject key = new JSONObject(c.getResponse());
return key.getString("status");
}
}
使用此类来构建您的请求并执行它:
public class RestClient { public enum RequestMethod {
GET,
POST
}
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
JSONObject jo = new JSONObject();
if(!params.isEmpty()){
for (int i = 0; i < params.size();i++)
{
jo.put(params.get(i).getName(),params.get(i).getValue());
}
StringEntity se = new StringEntity(jo.toString());
se.setContentType("text/xml");
se.setContentEncoding( new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
request.setEntity(se);
//request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
private void executeRequest(HttpUriRequest request, String url)
{
//HttpClient client = new DefaultHttpClient();
HttpClient client = HttpClientFactory.getThreadSafeClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
编辑:
哦,还有HttpClientFactory:
// Should be thread safepublic class HttpClientFactory {
private static DefaultHttpClient client;
public synchronized static DefaultHttpClient getThreadSafeClient() {
if (client != null)
return client;
client = new DefaultHttpClient();
ClientConnectionManager mgr = client.getConnectionManager();
HttpParams params = client.getParams();
client = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
mgr.getSchemeRegistry()), params);
return client;
}
}
以上是 使用Java for Android的HTTP API请求 的全部内容, 来源链接: utcz.com/qa/408572.html