2015-07-13 8 views
7

Im migrazione di un servizio da un normale server di dominio DNS a un unico server IP e questo fornisce un servizio di JSON per la mia app, il problema è che posso recuperare il JSONArray con il seguente codice nel nuovo URL:Impossibile recuperare JSONArray dal server IP ma posso farlo da un normale server?

protected JSONArray doInBackground(String... arg0) { 
       String reponse; 

       try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(url); 
        HttpResponse responce = httpclient.execute(httppost); 
        HttpEntity httpEntity = responce.getEntity(); 
        reponse = EntityUtils.toString(httpEntity); 
        return new JSONArray(reponse); 
        //With the oldURL I printed the JSON as a string and everithing OK but the new URL returns a null string of JSON 
       }catch(Exception e){ 
        e.printStackTrace(); 

       } 


       return null; 
      } 

String newurlexample = "http://111.22.333.44:1234/FOLD/blablabla"; 

String oldurl = "https:/example.com/FOLD/file.json"; 

e ottengo il seguente registro:

07-13 17:47:02.142: W/System.err(18824): org.json.JSONException: Value Method of type java.lang.String cannot be converted to JSONArray 
07-13 17:47:02.145: W/System.err(18824): at org.json.JSON.typeMismatch(JSON.java:111) 
07-13 17:47:02.145: W/System.err(18824): at org.json.JSONArray.<init>(JSONArray.java:96) 
07-13 17:47:02.146: W/System.err(18824): at org.json.JSONArray.<init>(JSONArray.java:108) 
07-13 17:47:02.146: W/System.err(18824): at com.karlol.***.Doctor_Fragment$GetData.doInBackground(Doctor_Fragment.java:171) 
07-13 17:47:02.146: W/System.err(18824): at com.karlol.***.Doctor_Fragment$GetData.doInBackground(Doctor_Fragment.java:1) 
07-13 17:47:02.147: W/System.err(18824): at android.os.AsyncTask$2.call(AsyncTask.java:288) 
07-13 17:47:02.147: W/System.err(18824): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
07-13 17:47:02.147: W/System.err(18824): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
07-13 17:47:02.147: W/System.err(18824): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
+0

La mia prima risposta è: perché non stai usando [Volley] (https://www.youtube.com/watch?v=yhv8l9F44qo)? – sonictt1

+0

Assicurati di poter accedere al tuo URL IP e restituisce JSON valido. Stampa anche la variabile "reponse" per vedere cosa restituisce il server – Sharj

+0

l'URL restituisce un JSON valido e la "risposta" restituisce: 'Metodo [POST] Non consentito, per favore assicurati che il REST MEthod [POST] per risorsa [il mio nuovo indirizzo] sia disponibile nell'altro lato! ' –

risposta

2

Dal titolo della tua domanda posso accorgo che c'è qualcosa di sbagliato tra l'URL che si stava utilizzando e il nuovo PI .. prima è necessario assicurarsi che il nuovo web -service fornisce lo stesso risultato di quello vecchio .. in qualsiasi modo puoi provare a recuperare i tuoi dati ing questo:

try{ 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     HttpResponse responce = httpclient.execute(httppost); 
     HttpEntity httpEntity = responce.getEntity(); 
     is = httpEntity.getContent(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
      is)); 

     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
     reponse = sb.toString(); 


     return new JSONArray(reponse); 
     //With the oldURL I printed the JSON as a string and everithing OK but the new URL returns a null string of JSON 

     }catch(Exception e){ 
      e.printStackTrace(); 

} 

EDIT:

Se uso comune server di hosting .. non è raro avere più siti web su stesso IP, differiscono tra loro solo per il nome del sito (cd hosting virtuale). Quello che stai facendo funzionerà solo nel caso in cui ci sia un singolo sito su un dato IP.

EDIT 2

È necessario testare il tuo webservice utilizzando un plugin RESTful (Chrome o Firefox) vale a dire, Advanced rest client

+0

Scusa ma "è" di che tipo è quella variabile? InputStream? –

+0

'InputStream statico è = null;' –

+0

il tuo servizio web non consente le richieste POST! puoi darmi un esempio di ciò che stai inviando? hai bisogno di testare il tuo webservice usando i plugin RESTful ... –

2

Abbiamo lo stesso problema prima di tentare di utilizzare questo. cambia quello dentro il tuo tentativo e prendi questo. spero che sia d'aiuto.

 FileCache filecache; 


String result=""; 
       HttpURLConnection conn = null; 
       String finalurl="http://111.22.333.44:1234/FOLD/blablabla"; 
       filecache = new FileCache(context); 
       File f = filecache.getFile(finalurl); 
       try { 
        URL url = new URL(finalurl); 
        conn = (HttpURLConnection) url.openConnection(); 
        conn.setConnectTimeout(30000); 
        conn.setReadTimeout(30000); 
        conn.setInstanceFollowRedirects(true); 
        InputStream is = conn.getInputStream(); 
        OutputStream os = new FileOutputStream(f); 
        Utils.CopyStream(is, os); 
        FileReader isr = new FileReader(f); 
        BufferedReader reader = new BufferedReader(isr); 
        StringBuilder sb = new StringBuilder(); 
        String line = null; 

        while ((line = reader.readLine()) != null) { 
         sb.append(line + "\n"); 
        } 
        result = sb.toString(); 
        is.close(); 
        os.close(); 
        conn.disconnect(); 
        return new JSONArray(result); 
       }catch (Exception ex) { 
        Log.e("Error", ex+"can't access" + finalurl + result); 
       } 

FileCache.java

import android.content.Context; 
import java.io.File; 

    /** 
    * Created by cristiana214 on 1/26/2015. 
    */ 
    public class FileCache { 
     private File cacheDir; 
     public FileCache(Context context) { 
      // Find the dir to save cached images 
      if (android.os.Environment.getExternalStorageState().equals(
        android.os.Environment.MEDIA_MOUNTED)) { 
       cacheDir = new File(context.getExternalCacheDir(),"folder/i"); 
      } else 
       cacheDir = context.getCacheDir(); 
      if (!cacheDir.exists()) 
       cacheDir.mkdirs(); 
     } 

     public File getFile(String url) { 
      String filename = String.valueOf(url.hashCode()); 
      File f = new File(cacheDir, filename); 
      return f; 
     } 
     public void clear() { 
      File[] files = cacheDir.listFiles(); 
      if (files == null) 
       return; 
      for (File f : files) 
       f.delete(); 
     } 
    } 

Utils.java

import java.io.InputStream; 
import java.io.OutputStream; 

/** 
* Created by cristiana214 on 1/26/2015. 
*/ 
public class Utils { 
    public static void CopyStream(InputStream is, OutputStream os){ 
     final int buffer_size=1024*10; 
     try{ 
      byte[] bytes=new byte[buffer_size]; 
      for(;;){ 
       int count=is.read(bytes, 0, buffer_size); 
       if(count==-1) 
        break; 
       os.write(bytes, 0, count); 
      } 
     } 
     catch(Exception ex){} 
    } 
} 
+0

@ Carlo A. López per favore commenta se hai già risolto i tuoi problemi. – Cristiana214

2

Secondo il vostro codice di errore

org.json.JSONException: Value Method of type java.lang.String cannot be converted to JSONArray 

si sta tentando di convertire una stringa JSONArray. c'è anche un puntatore all'attività doInBackground, riga 171, quindi dovresti assolutamente controllare questa linea. Credo che il problema è di circa queste righe:

reponse = EntityUtils.toString(httpEntity); 
return new JSONArray(reponse); 
1

controllare questo riga nel messaggio di registro:

W/System.err (18824): org.json.JSONException: Valore Metodo di tipo java.lang.String non può essere convertito in JSONArray

Si ottiene questa eccezione perché la risposta dal server che si sta ricevendo non è formattata come formato JSON. Pertanto, quando si tenta di convertire la stringa di risposta in JSONArray, viene lanciata la suddetta JSONException.

Ora la soluzione per il problema è: è necessario assicurarsi che la risposta sia formattata come il formato JSON corretto. E registra la tua risposta prima di analizzare a JSON con cui puoi verificare che la risposta sia corretta o meno.

Spero che questo ti aiuta :) Grazie

+0

Le informazioni non erano in formato JSON perché non stava ricevendo alcuna informazione! Il problema era la richiesta. –

2

Se questo aiuta qualcuno, ho dovuto cambiare la richiesta a un GET invece di POST e questo codice funzionato perfettamente, anche se non potevo andare al lavoro la richiesta POST.

try { 
        URL obj = new URL("http://anIPaddress/REST/Folder/Consult?Operation=AnOperation"); 
        HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
//con default method is GET 
        con.setRequestProperty("Accept", "application/json"); 
        con.setRequestProperty("Content-Type", "application/json"); 
        int responseCode = con.getResponseCode(); 
        Log.v("Lolo", "\nSending 'GET' request to URL : " + con.getURL()); 
        Log.v("Lolo", "RESPONSE CODE : " + responseCode); 
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
        String inputLine; 
        StringBuffer response = new StringBuffer(); 
        while ((inputLine = in.readLine()) != null) { 
         response.append(inputLine); 
        } 
        in.close(); 

        return new JSONArray(response.toString()); 
    } 

Grazie mille per le vostre risposte e il vostro aiuto.