gpt4 book ai didi

java - jackson 未处理的异常?

转载 作者:行者123 更新时间:2023-11-29 20:50:46 28 4
gpt4 key购买 nike

我是 android 编程的新手,我正在关注这个 tutorial创建 GCM 服务器程序。但是,我遇到了一个令人沮丧的错误,非常感谢任何帮助。

这是我的 POST2GCM 类:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import com.fasterxml.jackson.databind.ObjectMapper;


public class POST2GCM extends Content {

private static final long serialVersionUID = 1L;

public static void post(String apiKey, Content content){

try{

// 1. URL
URL url = new URL("https://android.googleapis.com/gcm/send");

// 2. Open connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

// 3. Specify POST method
conn.setRequestMethod("POST");

// 4. Set the headers
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "key="+apiKey);

conn.setDoOutput(true);

// 5. Add JSON data into POST request body

//`5.1 Use Jackson object mapper to convert Contnet object into JSON
ObjectMapper mapper = new ObjectMapper();

// 5.2 Get connection output stream
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());

// 5.3 Copy Content "JSON" into
mapper.writeValue(wr, content);

// 5.4 Send the request
wr.flush();

// 5.5 close
wr.close();

// 6. Get the response
int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// 7. Print result
System.out.println(response.toString());

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

我已经包含了“jackson-databind-2.5.1.jar”文件,但我收到了错误:

Unhandled Exception: com.fasterxml.jackson.databind.JsonMappingException

在线mapper.writeValue(wr, content);

是什么导致了这个异常,我该如何解决?

最佳答案

jackson-databind是一个通用数据绑定(bind)包,适用于流式 API (jackson-core) 实现。这就是为什么你需要添加 jackson-core并捕获 3 个异常。 writeValue方法抛出 IOExceptionJsonGenerationExceptionJsonMappingException

try {
mapper.writeValue(wr, content);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

希望对你有用。

关于java - jackson 未处理的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203130/

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