![](/img/trans.png)
[英]How to send json data from android app and receive it in rest web service running in jersey?
[英]Connecting to Jersey REST Web Service from Android
我創建了簡單的REST Web服務,該服務從客戶端獲取三個字符串並將其保存到數據庫中。 從Java客戶端應用程序可以正常工作。
現在,我想在Android設備上執行相同操作。 從我的設備連接到服務並執行相同操作的最佳方法是什么?
我是Android的新手,在網上進行了很多搜索,只是找不到足夠簡單的東西來理解如何做。 希望有人能幫忙。
RESTLocationService.java:
@Path("/data")
public class RESTLocationService {
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
public Response createDataInJSON(JSONObject data) throws JSONException {
String lon = data.getString("lon");
String lat = data.getString("lat");
String dateTime = data.getString("dateTime");
String location = "Longitude: " + lon + ", latitude: " + lat
+ ", time: " + dateTime + ".";
DataHiber dataHiber = new DataHiber(lon, lat, dateTime);
DBUtils.saveLocations(dataHiber);
return Response.status(201).entity(location).build();
}
}
RESTLocationClient.java:
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://192.168.111.77:8080/TebLocationService/rest/data/post");
String longy = "46.8888778877";
String latty = "12.9485495894859";
String timey = "29/03/2015 14:03";
JSONObject obj = new JSONObject();
obj.put("lon", longy);
obj.put("lat", latty);
obj.put("dateTime", timey);
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, obj);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
System.out.println("Output from Server .... \n");
String output = response.getEntity(String.class);
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
我找到了解決方案,但是大多數類都已棄用。 目前工作正常,將嘗試找到更好的解決方案並將其發布在此處。
Looper.prepare();
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(),
10000);
HttpResponse response;
JSONObject obj = new JSONObject();
String timey = DateFormat.getDateTimeInstance().format(new Date());
try {
HttpPost post = new HttpPost(SERVICE_URL);
obj.put("lon", longitude);
obj.put("lat", latitude);
obj.put("dateTime", timey);
StringEntity se = new StringEntity(obj.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(se);
response = client.execute(post);
if (response != null) {
InputStream in = response.getEntity().getContent();
}
} catch (Exception e) {
e.printStackTrace();
}
Looper.loop();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.