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");
您好我在调用java.lang.IllegalStateException: Cannot set method after connection is made
方法时遇到setRequestProperty
错误,但是当我在连接之前调用此方法时,我得到NullPointerException
因为con
为空。我该怎么做才能解决这个问题?
答案 0 :(得分:1)
请检查来自Google的此网址:http://developer.android.com/reference/java/net/HttpURLConnection.html
在设置标题之前,可以使用openConnection()
方法。以下是文档中的步骤:
setDoOutput(true)
进行配置。通过写入getOutputStream()
返回的流来传输数据。getInputStream()
返回的流中读取响应主体。如果响应没有正文,则该方法返回空流。HttpURLConnection
关闭disconnect()
。断开连接释放连接所拥有的资源,以便关闭或重用它们。但是,如果问题仍然存在,您可以尝试调试代码并检查connection.connected私有标志以查看它变为真的位置;在调用getContentType()
方法后,我遇到了类似的问题。
否则您只需切换到HttpClient API:
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
....
答案 1 :(得分:0)
请勿使用网址的便捷方法,使用HttpURLConnection或其他库。
答案 2 :(得分:0)
这可能有效:
URL url = new URL(urlStr);
con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Authorization", q);
con.setRequestProperty("GData-Version", "3.0");