无法从IP服务器检索JSONArray,但我可以从普通服务器?

时间:2015-07-13 22:49:39

标签: android json httpclient

我正在将服务从普通域DNS服务器迁移到仅IP服务器,这为我的应用程序提供了json服务,问题是我无法使用新URL中的以下代码检索JSONArray:

 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";

我得到以下日志:

    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)

5 个答案:

答案 0 :(得分:2)

从你问题的标题我可以注意到你使用的URL和新的ip之间有什么问题。首先你需要确保你的新网络服务提供与旧网站相同的结果。 您可以尝试使用此方法检索数据:

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();

}

编辑:

如果您使用共享托管服务器..在同一IP上拥有多个网站并不罕见,只能通过网站名称(所谓的虚拟主机)进行区分。您所做的只适用于给定IP上有单个站点的情况。

编辑2

您需要使用RESTful插件(chrome或firefox)测试您的网络服务,即Advanced rest client

答案 1 :(得分:2)

在尝试使用此功能之前,我们遇到了同样的问题。改变你的尝试中的一个并抓住这个。希望能帮助到你。

      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){}
    }
}

答案 2 :(得分:2)

根据您的错误代码

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

您正在尝试将String转换为JSONArray。 还有一个指向doInBackground任务的指针,第171行,所以你一定要检查这一行。 我猜问题就在于这些问题:

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

答案 3 :(得分:2)

如果这对某人有帮助,我必须将请求更改为GET而不是POST,并且此代码工作正常,但我无法处理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());
    }

非常感谢您的回答和帮助。

答案 4 :(得分:1)

在日志消息中选中此行:

  

W / System.err(18824):org.json.JSONException:类型java.lang.String的值方法无法转换为JSONArray

您收到此异常,因为您收到的服务器响应未格式化为JSON格式。因此,当您尝试将响应字符串转换为JSONArray时,会抛出上述JSONException。

现在您的问题的解决方案是:您需要确保将响应格式化为正确的JSON格式。并在解析为JSON之前记录您的响应,通过它您可以检查响应是否正确。

希望这可以帮助你:) 感谢