Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/182.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 将JSON发布到服务器并接收响应_Java_Android_Json_Post_Httpurlconnection - Fatal编程技术网

Java 将JSON发布到服务器并接收响应

Java 将JSON发布到服务器并接收响应,java,android,json,post,httpurlconnection,Java,Android,Json,Post,Httpurlconnection,我有一个名为findMeareStaturantDao的类,它包含一些方法,这些方法将在我的活动中使用AsyncTask内部类对服务器进行网络调用。我的请求后方法有问题,如下所示: @Override public String findMeARestaurant(List<CheckboxDTO> filters) { String inputLine; String errors; String result;

我有一个名为
findMeareStaturantDao
的类,它包含一些方法,这些方法将在我的活动中使用
AsyncTask
内部类对服务器进行网络调用。我的
请求后方法有问题,如下所示:

@Override
    public String findMeARestaurant(List<CheckboxDTO> filters) {
        String inputLine;
        String errors;
        String result;
        try
        {
            // For each CheckboxDTO, get the Id and add it to JSONArray
            JSONArray checkboxJSONArray = new JSONArray();
            for (CheckboxDTO checkbox : filters)
            {
                try
                {
                    // Create JSONObject
                    JSONObject object = new JSONObject();
                    // Build the object
                    object.put("id", checkbox.getId());
                    // Add object to JSONArray
                    checkboxJSONArray.put(object);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }

            // Put JSONArray into wrapping JSONObject
            JSONObject serverObject = new JSONObject();
            try
            {
                // Create wrapping JSONObject
                serverObject.put("filtersIds", checkboxJSONArray);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

            // Create URL object to hold URL
            URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
            // Create connection to server
            HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();

            // Set request method and timeouts
            connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setChunkedStreamingMode(0);
            connection.setDoOutput(true);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);

            // Connect to server
            connection.connect();

            // Create Writer
            Writer writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
            writer.write(String.valueOf(serverObject));

            // Close Writer
            writer.close();


            // Create InputStreamReader to read response from server
            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");

            // Create BufferedReader to read through InputStream
            BufferedReader reader = new BufferedReader(streamReader);
            // Create StringBuilder to hold our result
            StringBuilder stringBuilder = new StringBuilder();

            // Check if the line read is null
            while ((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            // Close out InputStream and BufferedReader
            reader.close();
            streamReader.close();

            // Set result to stringBuilder
            result = stringBuilder.toString();
            connection.disconnect();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }

        return result;
    }
@覆盖
公共字符串FindMeareStarant(列表筛选器){
字符串输入线;
字符串错误;
字符串结果;
尝试
{
//对于每个CheckboxDTO,获取Id并将其添加到JSONArray
JSONArray checkboxJSONArray=新的JSONArray();
for(复选框DTO复选框:过滤器)
{
尝试
{
//创建JSONObject
JSONObject对象=新的JSONObject();
//构建对象
put(“id”,checkbox.getId());
//将对象添加到JSONArray
checkboxJSONArray.put(对象);
}
捕获(例外e)
{
e、 printStackTrace();
}
}
//将JSONArray放入包装JSONObject中
JSONObject serverObject=新的JSONObject();
尝试
{
//创建包装JSONObject
put(“filtersIds”,checkboxJSONArray);
}
捕获(例外e)
{
e、 printStackTrace();
}
//创建URL对象以保存URL
URL FINDMEARESTAURATURL=新URL(FINDMEARESTAURATURL);
//创建到服务器的连接
HttpURLConnection connection=(HttpURLConnection)findMeareStarurantur.openConnection();
//设置请求方法和超时
connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
setRequestProperty(“内容类型”、“应用程序/json;utf-8”);
setRequestProperty(“接受”、“应用程序/json”);
connection.setChunkedStreamingMode(0);
connection.setDoOutput(真);
setReadTimeout(读取超时);
connection.setConnectTimeout(连接超时);
//连接到服务器
connection.connect();
//创作作家
Writer Writer=newbufferedwriter(newoutputstreamwriter(connection.getOutputStream());
writer.write(String.valueOf(serverObject));
//亲密作家
writer.close();
//创建InputStreamReader以从服务器读取响应
InputStreamReader streamReader=新的InputStreamReader(connection.getInputStream(),“utf-8”);
//创建BufferedReader以读取InputStream
BufferedReader reader=新的BufferedReader(streamReader);
//创建StringBuilder以保存结果
StringBuilder StringBuilder=新的StringBuilder();
//检查读取的行是否为空
而((inputLine=reader.readLine())!=null){
stringBuilder.append(inputLine);
}
//关闭InputStream和BufferedReader
reader.close();
streamReader.close();
//将结果设置为stringBuilder
结果=stringBuilder.toString();
连接断开();
}
捕获(IOE异常)
{
e、 printStackTrace();
返回null;
}
返回结果;
}

该方法是POST,当我运行应用程序时,它似乎将
JSON服务器对象
发送到服务器,但在
InputStreamReader
上失败,并返回一个
FileNotFoundException
。服务器是由合作伙伴为此项目设置的,并表示API的这一部分应该正常工作。我是不是错过了一些发帖请求?我是否需要做一些不同的事情来读取服务器的响应?任何帮助都将不胜感激

这个问题的解决方案是如何在
POST
请求中将数据发送到服务器。在建立连接之前,我必须将过滤器的ID添加到我的URL,从而将其发送到服务器。我修改过的方法遍历每个
CheckboxDTO
,捕获Id,然后将其添加到数组中,然后将其添加到URL中:

@Override
    public String findMeARestaurant(List<CheckboxDTO> filters) {
        String inputLine;
        String result;
        try
        {

            // For each CheckboxDTO, get the Id and add it to String Array
            int checkboxArray[] = new int[filters.size()];
            int i = 0;
            for (CheckboxDTO checkbox : filters)
            {
                try
                {
                    int id = checkbox.getId();
                    checkboxArray[i] = id;
                    i++;
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }

            }

            // Add filters to end of URL for POST Request
            findMeARestaurantsURL += "?filterIds=";
            for (i = 0; i < checkboxArray.length; i++)
            {
                if (i+1 != checkboxArray.length)
                {
                    findMeARestaurantsURL += checkboxArray[i] + ",";
                }
                else
                {
                    findMeARestaurantsURL += checkboxArray[i];
                }
            }
            // Create URL object to hold URL
            URL findMeARestaurantURL = new URL(findMeARestaurantsURL);
            // Create connection to server
            HttpURLConnection connection = (HttpURLConnection) findMeARestaurantURL.openConnection();

            // Set request method and timeouts
            connection.setRequestMethod(FIND_RESTAURANT_REQUEST_METHOD);
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setChunkedStreamingMode(0);
            connection.setDoOutput(true);
            connection.setReadTimeout(READ_TIMEOUT);
            connection.setConnectTimeout(CONNECTION_TIMEOUT);

            // Connect to server
            connection.connect();

            // Create InputStreamReader to read response from server
            InputStreamReader streamReader = new InputStreamReader(connection.getInputStream(), "utf-8");

            // Create BufferedReader to read through InputStream
            BufferedReader reader = new BufferedReader(streamReader);
            // Create StringBuilder to hold our result
            StringBuilder stringBuilder = new StringBuilder();

            // Check if the line read is null
            while ((inputLine = reader.readLine()) != null){
                stringBuilder.append(inputLine);
            }

            // Close out InputStream and BufferedReader
            reader.close();
            streamReader.close();

            // Set result to stringBuilder
            result = stringBuilder.toString();
            connection.disconnect();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }

        return result;
    }
@覆盖
公共字符串FindMeareStarant(列表筛选器){
字符串输入线;
字符串结果;
尝试
{
//对于每个CheckboxDTO,获取Id并将其添加到字符串数组中
int checkboxArray[]=新的int[filters.size()];
int i=0;
for(复选框DTO复选框:过滤器)
{
尝试
{
int id=checkbox.getId();
checkboxArray[i]=id;
i++;
}
捕获(例外e)
{
e、 printStackTrace();
}
}
//将筛选器添加到POST请求的URL结尾
findMeARestaurantsURL+=“?filterIds=”;
对于(i=0;i