Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SendHttpPost正在带回空JSONObject_Java_Android_Json_Http Post - Fatal编程技术网

Java SendHttpPost正在带回空JSONObject

Java SendHttpPost正在带回空JSONObject,java,android,json,http-post,Java,Android,Json,Http Post,我已经整理了几乎所有关于StackOverflow的JSON httppost教程和问题,我想我可能快疯了。有一次,我的Android应用程序在提交一个JSONObject并接收一个JSONObject之后完美地拉下数据并显示出来。现在,在失去了一天的编码后,我无法让它再次工作 我第一次使用它作为基础,然后它就开始工作了,那么有人能告诉我为什么在HttpClient.java中会出现空错误吗 最新消息:现在似乎可以工作了。但是接收到的JSON应该看起来像,而它包含的只是{mainSearchRe

我已经整理了几乎所有关于StackOverflow的JSON httppost教程和问题,我想我可能快疯了。有一次,我的Android应用程序在提交一个JSONObject并接收一个JSONObject之后完美地拉下数据并显示出来。现在,在失去了一天的编码后,我无法让它再次工作

我第一次使用它作为基础,然后它就开始工作了,那么有人能告诉我为什么在HttpClient.java中会出现空错误吗

最新消息:现在似乎可以工作了。但是接收到的JSON应该看起来像,而它包含的只是{mainSearchResult:[]}。想法

注意:是的,我有我所有的进口,可以找到LogCat。我只使用Java和Android编程了大约3周,所以请尽可能清楚简单地解释,希望不要依赖其他StackOverflow帖子来解释,因为我向你保证,我已经读过了

public class HttpClient {

public static final String TAG = HttpClient.class.getSimpleName();

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}


private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     * 
     * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

我使用不同的convertStreamToString方法:

 private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
在此之后,请尝试打印响应,该响应位于您的try-Catch范围内:

String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
Log.d("Reponse from request:",result); //Where you print to LogChat theresponse
然后我会尝试将字符串解析为JSONObject

JSONObject jObject = new JSONObject(result);             
   if(result!=null)
   {
    //Here is where you do your thing....
   }

看起来resultString不是有效的json对象,请尝试打印resultString或调试应用程序以查看其值。您也可以考虑在FET catch之外使用ReultStand变量,如果遇到错误,可以打印出来。另外,在try-catch中添加一个JSONException,以便缩小调试的执行选项类型。使用其他信息更新我无法告诉您,它与从何处检索数据、传递数据的参数等有关。。。我会说,找出http调用是什么,然后在浏览器中进行测试,看看是否可以从那里得到结果,并从这个角度进行操作。除非我弄错了,convertStreamToString方法正是我所使用的,一个字符对一个字符。另外,我已经记录了convertSTreamToString的结果,在这样做时,仍然会得到{mainSearchResult:[]}的字符串。是的,我现在看到了。很抱歉,响应是空的吗?你能展示一下你试图解析的JSON吗?要查看我试图下拉的JSON数据,以及它应该如何显示,请参阅原始帖子中的更新。很明显,他们有一些服务器问题,但是现在我收到的不是实际的json数据,而是实际的HTML,它构成了错误页面,表示在他们的服务器上找不到该文件。
May this help you.

 // Creating JSON Parser instance
        JSONParser jParser = new JSONParser();

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);
        JsonArray jsonArray=json.getJSONArray("mainSearchResult");
String strAudio=jsonArray.getJSONObject(0).getString("AudioStr");//move the loop towards it upto jsonArray.length() and get all the string in the same manner

  public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }