POST JSON 到服务器并接收响应
Posted
技术标签:
【中文标题】POST JSON 到服务器并接收响应【英文标题】:POST JSON to Server and Receive Response 【发布时间】:2020-03-25 09:13:11 【问题描述】:我有一个名为FindMeARestaurantDAO
的类,它包含的方法可以在我的Activity 中使用AsyncTask
内部类对服务器进行网络调用。我的POST request Method
有问题,如下:
@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;
该方法是 POST,当我运行我的应用程序时,它似乎将JSON serverObject
发送到服务器,但它在InputStreamReader
上失败并返回FileNotFoundException
。服务器是由该项目的合作伙伴设置的,并表示 API 的这一部分应该可以工作。我错过了 POST 请求的内容吗?我需要做一些不同的事情来读取服务器的响应吗?任何帮助将不胜感激。
【问题讨论】:
我强烈建议使用 Volley 来进行 API 操作。简单且易于实施。 - developer.android.com/training/volley @Reaz Murshed,我很欣赏这个建议。我将研究实现它来处理网络请求。我实际上想通了为什么这行不通;我试图发布错误类型的数据。原来我必须在 URL 的末尾发送数据才能接收响应。现在一切正常 很高兴知道你让它工作了。请将您的解决方案也作为答案发布。 【参考方案1】:这个问题的解决方案是我如何通过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;
服务器使用Spring框架,据我的伙伴说,没有使用JSONObject
。
【讨论】:
以上是关于POST JSON 到服务器并接收响应的主要内容,如果未能解决你的问题,请参考以下文章
向服务器发出 JSON POST 请求,接收二进制响应(Excel 文件),如何下载?
iPhone- 在 POST 中将 JSON 对象发送到 PHP 服务器并从服务器获取响应