异步任务的消息与Java Servlet交换

异步任务的消息与Java Servlet交换,第1张

概述我有一个简单的应用程序通过Async任务与其Servlet后端进行通信.我在理解消息如何被包装以及如何 *** 纵这些消息的数据结构方面遇到了一些麻烦.我想要做的是接收多个对象或多个异构信息.我的代码:publicclassMyServletextendsHttpServlet{ArrayList<Tour>m_tours;@

我有一个简单的应用程序通过Async任务与其Servlet后端进行通信.
我在理解消息如何被包装以及如何 *** 纵这些消息的数据结构方面遇到了一些麻烦.
我想要做的是接收多个对象或多个异构信息.
我的代码:@H_403_4@

public class MyServlet extends httpServlet {    ArrayList<Tour> m_tours;    @OverrIDe    public voID doGet(httpServletRequest req, httpServletResponse resp)        throws IOException {    resp.setContentType("text/plain");    resp.getWriter().println("Please use the form to POST to this url");    }    @OverrIDe    public voID doPost(httpServletRequest req, httpServletResponse resp) throws IOException {    String order = req.getParameter("order");    resp.setContentType("text/plain");    if (order == null) {        resp.getWriter().println("Please enter a name");    }      resp.getWriter().println("yay name received");      ArrayList<Tour> m_tours = getTours(); //returns a populated ArrayList of custom Tour objects      resp.getWriter().print(m_tours);}    private voID getTours(){        //some code here    }}`

我的Async任务类:

class ServletPostAsyncTask extends AsyncTask<Pair<Context, String>, VoID, String> {private Context context;@OverrIDeprotected String doInBackground(Pair<Context, String>... params) {    context = params[0].first;    String order = params[0].second;    String[] url = new String[3];    url[0] = "http://192.168.169.85:8080/hello";    url[1] = "http://10.0.2.2:8080/hello";    url[2] = "http://192.168.1.102:8080/hello";    httpClIEnt httpClIEnt = new DefaulthttpClIEnt();     httpPost httpPost = new httpPost(url[2]);    List<nameValuePair> nameValuePairs = new ArrayList<>(1);    nameValuePairs.add(new BasicnameValuePair("order", order));        try {            // Add name data to request            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));            // Execute http Post Request            httpResponse response = httpClIEnt.execute(httpPost);            httpentity entity = response.getEntity();            if (response.getStatusline().getStatusCode() == 200) {                return EntityUtils.toString(entity);            }                return "Error: " + response                        .getStatusline()                        .getStatusCode() + " " + response                        .getStatusline().getReasonPhrase();        } catch (ClIEntProtocolException e) {            return e.getMessage();        } catch (IOException e) {            return e.getMessage();        }    }@OverrIDeprotected voID onPostExecute(String result) {       String result1 = "Response: "+result;           Toast.makeText(context, result1, Toast.LENGTH_LONG).show();    }}

响应消息将ArrayList作为文本返回:

 Response: yay name received packagename@objectkey1 packagename@objectkey2 packagename@objectkey3 ... packagename@objectkeyn

但相反,我想要的是将它原样存储为ArrayList.
如何配置我的异步任务以接收我的m_tours ArrayList并将其存储在某处以供进一步使用?
此外,如何配置它以接收多个对象?

*编辑*

我按照@orip的建议尝试使用Gson,设置Async任务如下:

@OverrIDeprotected String doInBackground(Pair<Context, String>... params) {    context = params[0].first;    String order = params[0].second;    String[] url = new String[3];    url[0] = "http://192.168.169.85:8080/hello";    url[1] = "http://10.0.2.2:8080/hello";    url[2] = "http://192.168.1.102:8080/hello";    // httpPost httpPost = new httpPost("http://semiotic-art-88319.appspot.com/hello");    httpClIEnt httpClIEnt = new DefaulthttpClIEnt(); //127.0.0.1 - 10.201.19.153    httpPost httpPost = new httpPost(url[2]);    List<nameValuePair> nameValuePairs = new ArrayList<>(1);    nameValuePairs.add(new BasicnameValuePair("order", order));    try {        // Add name data to request        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));        // Execute http Post Request        httpResponse response = httpClIEnt.execute(httpPost);        if (response.getStatusline().getStatusCode() == 200) {            httpentity entity = response.getEntity();            return EntityUtils.toString(entity);        }        return "Error: " + response                .getStatusline()                .getStatusCode() + " " + response                .getStatusline().getReasonPhrase();    } catch (ClIEntProtocolException e) {        return e.getMessage();    } catch (IOException e) {        return e.getMessage();    }}@OverrIDeprotected voID onPostExecute(String JsonResponse) {    Gson gson = new Gson();    tours = (gson.fromJson(JsonResponse, Tours.class));    Toast.makeText(context, JsonResponse, Toast.LENGTH_LONG).show();}

在服务器端:

@OverrIDepublic voID doPost(httpServletRequest req, httpServletResponse resp) throws IOException {    String asyncmessage = req.getParameter("order");    if(asyncmessage.equals("tours")){        m_tours = getTours();  //ArrayList<Tour> m_tours;        Tours tours = new Tours(m_tours);        resp.setContentType("application/Json");        PrintWriter out = resp.getWriter();        out.print(new Gson().toJson(tours));        out.flush();        resp.getWriter().print(m_tours);    }}

但是我收到一个错误:

03-23 13:27:09.523  32387-32387/madapps.bicitourbo E/AndroIDRuntime﹕ FATAL EXCEPTION: mainProcess: madapps.bicitourbo, PID: 32387com.Google.gson.JsonSyntaxException: com.Google.gson.stream.MalformedJsonException: Use JsonReader.setLenIEnt(true) to accept malformed JsON at line 1 column 692 path $        at com.Google.gson.Gson.assertFullConsumption(Gson.java:786)        at com.Google.gson.Gson.fromJson(Gson.java:776)        at com.Google.gson.Gson.fromJson(Gson.java:724)        at com.Google.gson.Gson.fromJson(Gson.java:696)        at madapps.bicitourbo.ServletPostAsyncTask.onPostExecute(ServletPostAsyncTask.java:92)        at madapps.bicitourbo.ServletPostAsyncTask.onPostExecute(ServletPostAsyncTask.java:36)        at androID.os.AsyncTask.finish(AsyncTask.java:632)        at androID.os.AsyncTask.access0(AsyncTask.java:177)        at androID.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)        at androID.os.Handler.dispatchMessage(Handler.java:102)        at androID.os.Looper.loop(Looper.java:149)        at androID.app.ActivityThread.main(ActivityThread.java:5257)        at java.lang.reflect.Method.invokeNative(Native Method)        at java.lang.reflect.Method.invoke(Method.java:515)        at com.androID.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)        at com.androID.internal.os.ZygoteInit.main(ZygoteInit.java:609)        at dalvik.system.NativeStart.main(Native Method) Caused by: com.Google.gson.stream.MalformedJsonException: Use JsonReader.setLenIEnt(true) to accept malformed JsON at line 1 column 692 path $

该行发生此错误:

Tour tours = (gson.fromJson(JsonResponse, Tours.class));

我做错了什么?

* EDIT2 *
解决了:

错误:引起:com.Google.gson.stream.MalformedJsonException:使用JsonReader.setLenIEnt(true)接受格式错误的JsON是因为我正在调用resp.getWriter().print()两次,这是建议的由@orip.谢谢!

解决方法:

将servlet的内容类型设置为application / Json并返回JsON字符串(例如,使用Gson或Jackson来序列化结果.

在AndroID端,您可以使用AndroID的内置JsON类反序列化JsON字符串,或者(更好)使用您在servlet中使用的相同库.

例如,如果Tour类似于:

public class Tour {  // some simple int/string/List fIElds}

您可以构建一个响应类,如:

public class Tours {  private List<Tour> tours;  // ...}

然后在服务器端(见this question,我在这里使用Gson):

List<Tour> listofTours = ...;Tours tours = new Tours(listofTours);response.setContentType("application/Json");PrintWriter out = response.getWriter();out.print((new Gson()).toJson(tours));out.flush();

在客户端:

String JsonResponse = ...;Tours tours = (new Gson()).fromJson(JsonResponse, Tours.class);

有一些优化要做,但这可以让你开始.
另外,考虑使用OkHttp进行http连接而不是使用httpClIEnt,您可能最终会得到更简单,更健壮的代码.

总结

以上是内存溢出为你收集整理的异步任务的消息与Java Servlet交换全部内容,希望文章能够帮你解决异步任务的消息与Java Servlet交换所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1099186.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存