GET请求在android 6中返回null

时间:2016-07-12 05:36:48

标签: android rest get

直升机,

我有一个设置,我可以成功地将json数据发布到数据库(mongodb)。但是为在Android应用程序中检索相同数据而编写的代码无效。该应用程序给出null。如果我从谷歌的REST API客户端尝试,GET正在工作。有谁可以帮忙。 这是我的代码:

Android代码:

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.HashMap;
import java.util.Map;


public class Main7Activity extends AppCompatActivity {
    public String username;
    public String result;
    EditText contents;
    //public String result;
    public EditText serial1;
    public String serial;
    StringBuilder content=new StringBuilder();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main7);
        Intent intentExtras = getIntent();
        Bundle extraBundle = intentExtras.getExtras();
        username=extraBundle.getString("username");
        serial1=(EditText)findViewById(R.id.serial);
        serial=serial1.getText().toString();
        contents=(EditText)findViewById(R.id.contents);
        }
    public void ret(View v) {

            serial=serial1.getText().toString();
            Toast.makeText(Main7Activity.this, ""+serial , Toast.LENGTH_LONG).show();
            if(TextUtils.isEmpty(serial))
            {
                serial1.setError("Please Enter the Serial Number");
            } else {
                try {
                    URL url = new URL("http://10.43.106.94:8080/SRNSmartLab/rest/service/getNEdata" + serial);
                System.out.println(url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                int responseCode = conn.getResponseCode();
                BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                System.out.println(in);
                if (in.readLine() == null) {
                    contents.setText("No data found");
                }
                String str1;
                while ((str1 = in.readLine()) != null) {
                    content.append(str1 + "\n");
                    contents.setText(content);
                }
                in.close();
                System.out.println(content.toString());
               } catch (Exception e) {
                result = e.getMessage();
                Toast.makeText(Main7Activity.this, "" + result, Toast.LENGTH_LONG).show();

            }

        }
    }
} 

代码:

@GET
    @Path("/getNEdata/{deviceId}")
    public Response getDeviceData(@PathParam("deviceId") String deviceId) {
        List deviceDataList = new ArrayList<String>();
        System.out.println("The data is " +deviceId);
        Mongo mongo;
        DBCollection collection;
        DB db;
        try {
            mongo = new Mongo("localhost", 27017);
            DB db = mongo.getDB("nedata");
            // connecting to 'SRN' collection
            collection = db.getCollection("nodeinfo");
            BasicDBObject t = new BasicDBObject();
            t.put("SerialNO", deviceId);
            DBCursor cursor = collection.find(t).limit(10);
            while (cursor.hasNext()) {
                deviceDataList.add(cursor.next());
            }
        } catch (Exception e) {
            return Response.status(500)
                    .entity("Exception Occured while getting device slist")
                    .build();
        }

        if (deviceDataList == null)
            return Response.status(204).entity("No content Found!").build();
        else
            return Response.status(200).entity(deviceDataList.toString())
                    .build();

    }

谢谢,阿尔比

1 个答案:

答案 0 :(得分:0)

添加以下内容后,空错误得到纠正:

private class GetClass extends AsyncTask<String, Void, Void> {
        private final Context context;
        public String url;
        public String displayParm;
        public GetClass(Context c) {
            this.context = c;
        }

        protected void onPreExecute() {
//        progress= new ProgressDialog(this.context);
//        progress.setMessage("Loading");
//        progress.show();
            Log.w("var23", "loading");
        }

protected Void doInBackground(String... params) {
            try {
                Log.w("var23", "doInBackground url : " + this.url);
//            final TextView outputView = (TextView) findViewById(R.id.showOutput);
                URL url = new URL( this.url );
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
                connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
                connection.setRequestProperty("accept", "application/json");
                int responseCode = connection.getResponseCode();
                Log.w("var23", "api hit in respomse"+String.valueOf(responseCode));
                final StringBuilder output = new StringBuilder("Request URL " + url);
                output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
                output.append(System.getProperty("line.separator") + "Type " + "GET");
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line = "";
                StringBuilder responseOutput = new StringBuilder();
                System.out.println("output===============" + br);
                while ((line = br.readLine()) != null) {
                    responseOutput.append(line);
                }
                Log.w("var24", "Result from API: " + responseOutput.toString());
                br.close();

                final JSONArray jObject = new JSONArray(responseOutput.toString());