java.lang.IllegalStateException:已经为setRequestProperty方法连接:Java

时间:2016-07-19 14:54:24

标签: java httpurlconnection

我创建了一个类,我正在创建一个HttpURLConnection对象,如果它传递了以下条件,则将该对象传递给另一个方法:

在此课程中,我传递usernamepasswordsenderId,以便在连接不为空时使用proxy连接到某个网址。

以下是Java类的完整代码:

public class SMSGenerator {
   public static HttpURLConnection sendSingleSMS(HttpURLConnection lconnection, String username,
       String password, String senderId,
       String mobileNo, String message) {
   try {
       String smsservicetype = "singlemsg"; // For single message.
       String query = "username=" + URLEncoder.encode(username)
               + "&password=" + URLEncoder.encode(password)
               + "&smsservicetype=" + URLEncoder.encode(smsservicetype)
               + "&content=" + URLEncoder.encode(message) + "&mobileno="
               + URLEncoder.encode(mobileNo) + "&senderid="
               + URLEncoder.encode(senderId);

       lconnection.setRequestProperty("Content-length", String.valueOf(query.length()));
       lconnection.setRequestProperty("Content-Type",
               "application/x-www-form-urlencoded");
       lconnection.setRequestProperty("User-Agent",
               "Mozilla/4.0 (compatible; MSIE 5.0; Windows 98; DigExt)");

       // open up the output stream of the connection
       DataOutputStream output = new DataOutputStream(lconnection.getOutputStream());

       // write out the data
       int queryLength = query.length();
       output.writeBytes(query);
       // output.close();

       // get ready to read the response from the cgi script
       DataInputStream input = new DataInputStream(lconnection.getInputStream());

       // read in each character until end-of-stream is detected
       for (int c = input.read(); c != -1; c = input.read()) {
           System.out.print((char) c);
       }
       input.close();
   } catch (Exception e) {
       System.out.println("Something bad just happened.");
       e.printStackTrace();
   }
   return lconnection;
}
public static boolean sendSMS(String mobilenumber, String msg) throws MalformedURLException, IOException {
   boolean flag = false;
   Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("xxxxxxxxxx", xx));
   URL surl = new URL("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
   HttpURLConnection connection = null;
   connection = (HttpURLConnection) surl.openConnection(proxy);
   connection.setDoInput(true);
   connection.setDoOutput(true);
   connection.setRequestMethod("POST");
   HttpURLConnection.setFollowRedirects(true);
   System.out.println("Response code " + connection.getResponseMessage());
   System.out.println("code : " + connection.getResponseCode() + " " + HttpURLConnection.HTTP_NOT_FOUND);
   if ("OK".equals(connection.getResponseMessage())) {
       System.out.println("in");
       SMSGenerator.sendSingleSMS(connection, "username", "password", "SMS", mobilenumber, msg);
//             System.out.println("Sent successful SMS");
       flag = true;

   } else if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
       System.out.println("Hiiii");
   } else if (connection.getResponseCode() == HttpURLConnection.HTTP_BAD_GATEWAY) {
       System.out.println("Hi 1");
   } else if (connection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
       System.out.println("Hi 2");
   }
//        System.out.println("");
   return flag;
}
public static void main(String[] args) throws IOException {
   new SMSGenerator().sendSMS("xxxxxxxxxx", "ManojYest1");
}
}

此代码的问题在于,如果我将if条件检查为:connection != null,则它会建立连接并正确调用方法。但是,如果我将responseCode检查为connection.getResponseCode() == HttpURLConnection.HTTP_OK,则会出现以下错误:

java.lang.IllegalStateException: Already connected
   at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:3013)

如何解决此错误?

2 个答案:

答案 0 :(得分:2)

因为连接不应该像这样使用。您尝试做的事情如下:

"Open" Connection
Get Response
|-> Connect (if not already connected)
|-> Read response data
setRequestProperty
|-> Check connected state - Oops! Already connected!

您应该如何使用UrlConnection。相反,它希望您执行以下操作:

"Open" Connection
setRequestProperty
|-> Check connected state - Not Connected
getOutputStream
|-> Connect
|-> Create and return output stream
Write request to output stream
Get Response
|-> Connect (if not already connected)
|-> Send (empty) request
|-> Read response data

您是否有理由要知道在发送数据之前您将获得OK回复?或者您只是尝试验证您是否已成功连接到端点?

openConnection没有导致连接对象实际连接到目标网址没有帮助...

答案 1 :(得分:-1)

在发布数据后编码获取响应代码时,它将起作用:

E.g。

responsecode  = con.getResponsecode();