gpt4 book ai didi

java - 将 JSON POST 到服务器并接收响应

转载 作者:行者123 更新时间:2023-12-01 19:47:45 29 4
gpt4 key购买 nike

我有一个名为 FindMeARestaurantDAO 的类,其中包含的方法将通过我的 Activity 中的 AsyncTask 内部类对服务器进行网络调用。我的 POST 请求方法 遇到问题,如下所示:

@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 请求的某些内容?我是否需要做一些不同的事情来读取服务器的响应?任何帮助将不胜感激。

最佳答案

此问题的解决方案是如何在 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

关于java - 将 JSON POST 到服务器并接收响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59110428/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com