【发布时间】:2023-03-20 17:26:01
【问题描述】:
HttpURLConnection con = null;
Response response = new Response();
String TAG = "HttpConHandler";
try{
/*
* IMPORTANT:
* User SHOULD provide URL Encoded Parms
*/
Log.p(TAG, "URL="+ urlStr);
String q=httpHeaders.get("Authorization");
URL url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", q);
con.setRequestProperty("GData-Version", "3.0");
嗨,当setRequestProperty 方法被调用时,我收到java.lang.IllegalStateException: Cannot set method after connection is made 错误,但是当我在连接之前调用此方法时,我得到NullPointerException,因为con 为空。我该怎么做才能解决这个问题?
【问题讨论】:
-
似乎很清楚。设置属性后打开连接
-
@Ovidiu Latcu 但我得到一个空指针异常,原因是 con 未初始化
-
您发布的代码与描述的不符。您没有调用
setResponseCode(),这是一个 servlet 方法,而不是HttpURLConnection方法,并且您也没有更改连接的方法,正如异常消息所建议的那样。显然,真正的问题是您以其他方式调用setRequestProperty()或setRequestMethod()或getOutputStream()。请贴出真实代码。
标签: java android httpconnection