Java jersey RESTful webservice requests(Java jersey RESTful Web 服务请求)
问题描述
我一直在关注有关宁静服务的教程,它运行良好.但是有些东西我还不太明白.看起来是这样的:
I've been following a tutorial about a restful service and it works fine. However there are something I dont quite understand yet. This is how it looks:
@Path("/hello")
public class Hello {
// This method is called if TEXT_PLAIN is request
@GET
@Produces( MediaType.TEXT_PLAIN )
public String sayPlainTextHello()
{
return "Plain hello!";
}
@GET
@Produces( MediaType.APPLICATION_JSON )
public String sayJsonTextHello()
{
return "Json hello!";
}
// This method is called if XML is request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version="1.0"?>" + "<hello> Hello Jersey" + "</hello>";
}
// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello()
{
return "<html> " + "<title>" + "Hello fittemil" + "</title>"
+ "<body><h1>" + "Hello!" + "</body></h1>" + "</html> ";
}
}
困扰我的是我无法使用正确的操作.当我从浏览器请求服务时,会调用相应的 sayHtmlHello() 方法.但现在我正在开发一个 android 应用程序,我想在 Json 中得到结果.但是当我从应用程序调用服务时,会调用 MediaType.TEXT_PLAIN 方法.我的 android 代码与此类似:
Whats bothering me is that I can't make use of the right operations. When I request the service from a browser the appropriate sayHtmlHello() method gets called. But now I am developing an android application which I want to get the result in Json. But when I call the service from the application, the MediaType.TEXT_PLAIN method gets called. My android code looks similar to this:
使用 android 发出 HTTP 请求
如何从我的 android 应用程序中调用使用 MediaType.APPLICATION_JSON 的方法?此外,我想让该特定方法返回一个对象,如果我也能在那里得到一些指导,那就太好了.
How can call the method which uses MediaType.APPLICATION_JSON from my android application? Further I would like to make that particular method return an object, would be great if I got some guidance there as well.
推荐答案
我有使用 Jersey 实现 REST in java (JAX-RS) 的个人经验.然后我通过一个 Android 应用程序连接到这个 RESTful Web 服务.
I have personally experience in implementing REST in java (JAX-RS) using Jersey. Then I connected to this RESTful Web Service via an Android application.
在您的 Android 应用程序中,您可以使用 HTTP 客户端库.它支持 POST、PUT、DELETE、GET 等 HTTP 命令.例如使用 GET 命令并以 JSON 格式或 TextPlain 传输数据:
In your Android application you can use HTTP Client library. It supports the HTTP commands such as POST, PUT, DELETE, GET. For example to use GET command and trasferring data in JSON format or TextPlain:
public class Client {
private String server;
public Client(String server) {
this.server = server;
}
private String getBase() {
return server;
}
public String getBaseURI(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
public String getBaseURIText(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpGet getRequest = new HttpGet(getBase() + str);
getRequest.addHeader("accept", "text/plain");
HttpResponse response = httpClient.execute(getRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}
}
然后在一个 android 类中你可以:
And then in an android class you can:
Client client = new Client("http://localhost:6577/Example/rest/");
String str = client.getBaseURI("Example"); // Json format
解析 JSON 字符串(或者可能是 xml)并在 ListView、GridView 和...中使用它
Parse the JSON string (or maybe xml) and use it in ListView, GridView and ...
我简要浏览了您提供的链接.那里有一个好点.您需要在 API 级别 11 或更高级别的单独线程上实现网络连接.查看此链接:HTTP 客户端 API 级别 11 或更高版本在 Android 中.
I took a short look on the link which you had provided. There was a good point there. You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.
这是我在客户端类中使用 HTTP 发布对象的方式:
This is the way that I post an object with HTTP in Client class :
public String postBaseURI(String str, String strUrl) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(getBase() + strUrl);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
在 REST WS 中,我将对象发布到数据库:
And in the REST WS, I post the object to the database:
@POST
@Path("/post")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response addTask(Task task) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(task);
session.getTransaction().commit();
return Response.status(Response.Status.CREATED).build();
}
这篇关于Java jersey RESTful Web 服务请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java jersey RESTful Web 服务请求
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01