Как передать переменную с помощью HttpURLConnection

У меня есть следующий код для получения содержимого URL-адреса.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication3;

/**
 *
 * @author Ravi
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class Main {

  /**
   * @param args
   */
  public static void main(String[] args) {
      HttpURLConnection connection = null;
      OutputStreamWriter wr = null;
      BufferedReader rd  = null;
      StringBuilder sb = null;
      String line = null;

      URL serverAddress = null;

      try {
          serverAddress = new URL("http://192.16.110.11:8084/RaviTest/index.jsp?id=3");
          //set up out communications stuff
          connection = null;

          //Set up the initial connection
          connection = (HttpURLConnection)serverAddress.openConnection();
          connection.setRequestMethod("GET");
          connection.setDoOutput(true);
          connection.setReadTimeout(10000);

          connection.connect();

          //get the output stream writer and write the output to the server
          //not needed in this example
          //wr = new OutputStreamWriter(connection.getOutputStream());
          //wr.write("");
          //wr.flush();

          //read the result from the server
          rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
          sb = new StringBuilder();

          while ((line = rd.readLine()) != null)
          {
              sb.append(line + '\n');
          }

          System.out.println(sb.toString());

      } catch (MalformedURLException e) {
          e.printStackTrace();
      } catch (ProtocolException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
      finally
      {
          //close the connection, set all objects to null
          connection.disconnect();
          rd = null;
          sb = null;
          wr = null;
          connection = null;
      }
  }
}

Но этот код копирует только содержимое указанного URL.

Вместо этого, если я хочу подключиться к странице jsp и могу ли я динамически получать значения, которые отправляются этой страницей JSP...

Например, если у меня есть страница http://192.16.110.51/WelcomeProject/index.jsp

Я должен иметь возможность передать переменную, и, в свою очередь, страница index.jsp вернет мне переменную, добавленную к приветственному миру, или выполнит некоторые манипуляции с переменной и отправит мне результат. Как я могу этого добиться?... Если не HttpURLConnection ..Есть ли какой-либо другой способ, с помощью которого я могу это сделать.


person user650521    schedule 10.04.2011    source источник


Ответы (2)


Это пример, измененный с: http://www.java2s.com/Code/JavaAPI/java.net/URLConnectionsetDoOutputbooleandooutput.htm (я удаляю ответную часть, возможно, вы действительно захотите ее вернуть)

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.URL;
import java.net.URLConnection;

public class MainClass {
  public static void main(String args[]) throws Exception {
    String query = "id=3";

    URLConnection uc = new URL("http://192.16.110.11:8084/RaviTest/index.jsp").openConnection();
    uc.setDoOutput(true);
    uc.setAllowUserInteraction(false);
    DataOutputStream dos = new DataOutputStream(uc.getOutputStream());

    // The POST line, the Accept line, and
    // the content-type headers are sent by the URLConnection.
    // We just need to send the data
    dos.writeBytes(query);
    dos.close();
  }

}
person Aleadam    schedule 10.04.2011
comment
Привет ... У вас есть wrtiitn dos.writeBytes (query), и я думаю, что это передает запрос на URL-адрес. Но как URL-адрес узнает о запросе? - person user650521; 10.04.2011
comment
@user650521 user650521 отправляется URLConnection OutputStream . Посмотрите, как определяется DataOutputStream dos. download.oracle.com/ javase/6/docs/api/java/net/ - person Aleadam; 11.04.2011

Когда вы используете http-клиент, вы как бы автоматизируете браузер. Браузер ничего не знает о jsp-страницах. Он не знает о java. Все, о чем он знает, это HTML и HTTP.

Если страница JSP отвечает на сообщения формы, вы можете отправить HTTP POST с параметрами формы.

Это намного проще с Apache Commons Httpclient, чем с необработанной JRE, поэтому я рекомендую прочитать об этом.

person bmargulies    schedule 10.04.2011