[英]Calling REST web services from android client
我正在android應用程序的后端實現RESTful Web服務。由於我是REST和Web服務的新手,請在執行對我的后端REST Web服務的POST請求時提供幫助。
我可以在android客戶端中使用以下代碼為POST請求調用RESTful Web服務(通過使用AsyncTask中的代碼)嗎?
如果沒有,請給我建議。 任何指向示例代碼和資源的鏈接都將受到贊賞!! 提前致謝 ...
package com.javacodegeeks.enterprise.rest.jersey.jerseyclient;
import com.javacodegeeks.enterprise.rest.jersey.Student;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class JerseyClient {
public static void main(String[] args) {
try {
Student st = new Student("Adriana", "Barrer", 12, 9);
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(
JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
Client client = Client.create(clientConfig);
WebResource webResource = client
.resource("http://localhost:9090/JerseyJSONExample/rest/jsonServices/send");
ClientResponse response = webResource.accept("application/json")
.type("application/json").post(ClientResponse.class, st);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println("Server response .... \n");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我尚未測試您的代碼,因此不確定是否可以正常工作。 但這是我的方法,您可以嘗試一下:
private String sendPostRequest(String payload, String url) {
StringEntity en = new StringEntity(payload);
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/json");
request.setEntity(en);
HttpResponse httpResponse = httpClient.execute(request);
HttpEntity entity = httpResponse.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
InputStream inputStream = bufHttpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
String response = "";
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
response = stringBuilder.toString();
return response;
}
檢查改造庫 ,它非常適合移動REST客戶端。 使用方法如下:首先聲明端點,如下所示:
public interface RestClient {
@POST("/post.php")
void postStudent(
@Field("firstname") String firstname,
@Field("lastname") String lastname,
@Field("birthday") String birthday,
Callback<Response> callback);
}
然后創建用於與支持者進行交互的客戶端端點:
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://your_server_address/")
.setRequestInterceptor(requestInterceptor).build();
RestClient client = restAdapter.create(RestClient.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.