如何从客户端调用一系列RESTFULES服务



我在Restful Web服务中是非常新的,并试图调用客户端的double [] []值数组。我可以使用XMLPullParser检索一行数组。我需要将整个数组致电客户端。请帮忙。IM Gona发布了REST Web服务代码和客户端代码。

REST Web服务 -

(资源类)

 import java.util.List;
 import javax.jws.WebService;
 import javax.ws.rs.GET;
 import javax.ws.rs.Path;
 import javax.ws.rs.Produces;
 import javax.ws.rs.core.MediaType;
 import org.mushtaq.javabrains.matrix.model.MatrixModel;
 import org.mushtaq.javabrains.matrix.service.MatrixService;

 @Path("/MatrixResource")
 @WebService
 public class MatrixResource {
 double [][] a,b;
    MatrixService ms = new MatrixService();
    @GET
    @Produces(MediaType.APPLICATION_XML)
    public List<MatrixModel> RandomArraynew (){
            a= ms.RandomArray(100);
            b= ms.RandomArray1(100);
            return ms.Multi(a,b);

        }

    }

(服务类)

 package org.mushtaq.javabrains.matrix.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.mushtaq.javabrains.matrix.model.MatrixModel;
import org.mushtaq.javabrains.matrix.resource.MatrixResource;
public class MatrixService {
public double[][] RandomArray(int n) {
        double[][] randomMatrix = new double[n][n];
        double[] randomArray = new double[n];
        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Integer r = rand.nextInt() % 100;
                randomMatrix[i][j] = Math.abs(r);
            }
        }
                 return randomMatrix;

    }

    public double[][] RandomArray1(int n) {
        double[][] randomMatrix1 = new double[n][n];
        double[] randomArray = new double[n];
        Random rand = new Random();
        rand.setSeed(System.currentTimeMillis());
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                Integer r = rand.nextInt() % 100;
                randomMatrix1[i][j] = Math.abs(r);
            }
        }
               return randomMatrix1;
}
    public List<MatrixModel> Multi(double a [][], double b[][]){
        if(a.length == 0) return new double [0][0];
        if(a[0].length != b.length) return null; //invalid dims
        int q = a[0].length;
        int m = a.length;
        int p = b[0].length;
        double ans[][] = new double[m][p];
        for(int i = 0;i < m;i++){
            for(int j = 0;j < p;j++){
                for(int k = 0;k < q;k++){
                    ans[i][j] += a[i][k] * b[k][j];
                }
            }
        }
          MatrixModel r= new MatrixModel(ans);
          ArrayList<MatrixModel> list = new ArrayList<>();
          list.add(r);
          return list;
    }
}

(模型类)

 package org.mushtaq.javabrains.matrix.model;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class MatrixModel {
    double [][] result;
    public MatrixModel(){
    }

    public MatrixModel(double [][] result){

        this.result=result;
    }
    public double[][] getResult() {
        return result;
    }
    public void setResult(double[][] result) {
        this.result = result;
    }
 }

上面三个是RestWebservice类,它应该在其中返回Double [] []值的数组。我可以通过url =" http://172.21.202.7:8080/matrix/webapi/matrixrixrixResource"在浏览器中完美地称其为浏览器。它以XML格式显示数组。我被卡住了,如何从客户端称呼整个数组。当我调用服务时,它仅显示一行数组。我的客户端代码如下。

客户端代码 -

(MyActivityClass)

 package com.example.Comp_Offloading;
 import android.app.ActionBar;
 import android.app.Activity;
 import android.content.Context;
 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 import android.widget.TextView;
 import android.widget.Toast;
 import java.io.IOException;
 import java.util.List;
 public class MyActivity extends Activity {
 TextView txt;
 TextView txt2;
 TextView txt3;
 EditText etxt, etxt2;
 Button bt, bt2;
 TextView output;
 ProgressBar pb;
 ActionBar ab;
 List<Matrix> matlist;
 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    txt = (TextView) findViewById(R.id.textView);
    txt2 = (TextView) findViewById(R.id.textView2);
    txt3=(TextView)findViewById(R.id.textView3);
    etxt=(EditText)findViewById(R.id.editText);
    etxt2=(EditText)findViewById(R.id.editText2);
    bt = (Button) findViewById(R.id.button);
    bt2 = (Button) findViewById(R.id.button2);
    //i = (ImageButton) findViewById(R.id.imageButton);

    bt2.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            etxt.setText("");
            etxt2.setText("");
            txt.setText("");
            etxt.requestFocus();
        }
    });

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isOnline())   
       {requestData("http://172.21.202.7:8080/matrix/webapi
        /MatrixResource");
            }
        }
    });}

private void requestData(String Uri) {
    MyTask task= new MyTask();
    task.execute(Uri);
}
protected void updateDisplay() {
    if (matlist != null) {
        for (Matrix matrix : matlist) {
            txt.append(matrix.getResult() + "");
        }

    }
}
protected boolean isOnline(){
    ConnectivityManager cm= (ConnectivityManager)
    getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netinfo=cm.getActiveNetworkInfo();
    if (netinfo != null && netinfo.isConnectedOrConnecting()) {
        return true;
    }
    else{
        Toast.makeText(this, "Network is not available", 
        Toast.LENGTH_LONG).show();
        return false;}
 }
    private class MyTask extends AsyncTask<String,String,String> {
    @Override
    protected void onPreExecute() {
        //updateDisplay("Starting Task...");
        //pb.setVisibility(View.VISIBLE);
    }
    @Override
    protected String doInBackground(String... params) {
        String content = null;
        try {
            content = HttpManager.getData(params[0]);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    protected void onPostExecute(String result) {
        matlist = MatrixXMLParser.parseFeed(result);
        updateDisplay();
        //pb.setVisibility(View.INVISIBLE);
    }

 }

}

(httpmanager class)

  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.URL;
  public class HttpManager {
    public static String getData(String Uri) throws IOException {
        BufferedReader reader = null;
        try {
            URL url = new URL(Uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            StringBuilder sb = new StringBuilder();
    reader= new BufferedReader(new  InputStreamReader(con.getInputStream()));
            String line;
            while((line= reader.readLine()) !=null){
                sb.append(line + "n");
            }
            return sb.toString();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally {
            if(reader !=null){
                reader.close();
            }
        }
    }
}
***(XMLPullparser Class)***

 package com.example.Comp_Offloading;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserFactory;
 import java.io.StringReader;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 public class MatrixXMLParser {
 public static List<Matrix> parseFeed(String content) {
    try {
        boolean inDataItemTag = false;
        String currenTagName = "";
        Matrix matrix = null;
        List<Matrix> matlist = new ArrayList<>();
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        XmlPullParser parser = factory.newPullParser();
        parser.setInput(new StringReader(content));
        int everntType = parser.getEventType();
        while (everntType != XmlPullParser.END_DOCUMENT) {
            switch (everntType) {
                case XmlPullParser.START_TAG:
                    currenTagName = parser.getName();
                    if (currenTagName.equals("result")) {
                        inDataItemTag = true;
                        matrix = new Matrix();
                        matlist.add(matrix);
                    }
                    break;
                case XmlPullParser.END_TAG:
                    if (parser.getName().equals("result")) {
                        inDataItemTag = false;
                    }
                    currenTagName = "";
                    break;
                case XmlPullParser.TEXT:
                    if (inDataItemTag && matrix != null) {
                        switch (currenTagName) {
  case "item":matrix.setResult(Double.parseDouble(parser.getText()));
  break;
                 default:
                 break;
                        }
                    }
                    break;
            }
            everntType = parser.next();
        }
        return matlist;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
 }
}
***(Model Class)***
 package com.example.Comp_Offloading;
 public class Matrix {
 private double item;
 public double getResult() {
    return item;
}
public void setResult(double result) {
    this.item = result;
}

}

请帮忙。检查并建议客户端代码中有什么问题。我应该添加什么来调用整个数组并在客户端显示。另外,如果除了XMLPullParser以外还有其他简单的方法,可以将整个数组显示为纯文本。谢谢

http响应不支持纯文本响应中的数组。您要么需要手动表示您的数组为字符串,要将返回类型更改为字符串,然后返回这样:

return Arrays.toString(arr);

或者您可以将数组转换为列表:return arrays.aslist(arr);

相关内容

  • 没有找到相关文章