当前位置: 技术问答>java相关
那位高手回答一下
来源: 互联网 发布时间:2015-10-28
本文导语: //问题是我在服务器上无法得到发送过去的字符串(服务器用text记录) //如果不包括带****号的几行时可以接收 //用post还有什么要注意的,没有error打印出来 String url="http://192.168.50.211/midlet/login.asp?logname=jacky&pwd=123"; Str...
//问题是我在服务器上无法得到发送过去的字符串(服务器用text记录)
//如果不包括带****号的几行时可以接收
//用post还有什么要注意的,没有error打印出来
String url="http://192.168.50.211/midlet/login.asp?logname=jacky&pwd=123";
String outstr="logname=fdf&pwd=123";
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
**** os=c.openOutputStream();
*****os.write(outstr.getBytes());
**** os.flush();
if(status!=HttpConnection.HTTP_OK)
System.out.println("error");
****os.close();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
result=b.toString();
System.out.println(result);
}catch(IOException e)
{
result="-2";
}
//如果不包括带****号的几行时可以接收
//用post还有什么要注意的,没有error打印出来
String url="http://192.168.50.211/midlet/login.asp?logname=jacky&pwd=123";
String outstr="logname=fdf&pwd=123";
try {
c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("IF-Modified-Since", "20 Jan 2001 16:19:14 GMT");
c.setRequestProperty("User-Agent","Profile/MIDP-1.0 Configuration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
**** os=c.openOutputStream();
*****os.write(outstr.getBytes());
**** os.flush();
if(status!=HttpConnection.HTTP_OK)
System.out.println("error");
****os.close();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
result=b.toString();
System.out.println(result);
}catch(IOException e)
{
result="-2";
}
|
GET和POST方法传递参数的方式不同,GET把参数直接写在URL里,而POST有专门的field(Entity Body)来放这些参数。详细解释和代码可惜参考下边的文章(别人写的):
[...] for example, under the GET method, the browser might initiate the HTTP transaction as follows:
GET HTTP/1.0 /cgi-bin/guestbook.pl?firstname=Joe&lastname=Schmoe
[...] The POST method says to use the body portion of the HTTP request to pass parameters. The same transaction with the POST method would read as follows:
POST HTTP/1.0 /cgi-bin/guestbook.pl
... [More headers here]
firstname=Joe&lastname=Schmoe
-- from the Webmaster In a Nutshell, 1e (which you should pick up if you write web programs a lot.. it will explain other headers you will run across.. another great resource is the newly finalized (just about) HTTP/1.1 standard RFC--grab the HTTP/1.0 RFC too--they are both in plain English)
So basically.. when you create the string of text to send over your Java socket (or type over telnet): 1) you first make all your headers, line by line. 2) then add a blank line.. (e.g. nn) 3) and then add the parameters on the next line (without returns) however long the parameter may be. The parameters and url needs to be urlencoded (all non plain text "X" in the stream will be replaced with "%NN" hex equivalent) for older browsers and old webservers. It's the "safe" way. GET and POST is universal, regardless of what language you use. With Java however, you should read some Java network/applet programming FAQs downloadable from the web to understand some quirks involving socket usage from a wide variety of browser JVM.
-- Li-fan Chen, July 26, 2000
--------------------------------------------------------------------------------
An important point with the POST method is that it requires the content-length. The GET method does not, but it is limited to 300 or so bytes in length and should be reproducible (always yield the same result). The second important point is to specify the correct MIME-encoding for the filetype you want to upload.
Find java code online from the book Core Servlets and JavaServer Pages This method, taken from Chap.17, represents an actionhandler that can be assigned to a "Submit" button on your Applet.
public void actionPerformed(ActionEvent event) {
try {
String protocol = currentPage.getProtocol();
String host = hostField.getTextField().getText();
String portString = portField.getTextField().getText();
int port;
try {
port = Integer.parseInt(portString);
} catch(NumberFormatException nfe) {
port = -1; // I.e., default port of 80
}
String uri = uriField.getTextField().getText();
URL dataURL = new URL(/tech-qa-java/protocol, host, port, uri/index.html);
URLConnection connection = dataURL.openConnection();
// Make sure browser doesn't cache this URL.
connection.setUseCaches(false);
// Tell browser to allow me to send data to server.
connection.setDoOutput(true);
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512); // Grows if necessary
// Stream that writes into buffer
PrintWriter out = new PrintWriter(byteStream, true);
String postData =
"firstName=" + encodedValue(firstNameField) +
"&lastName=" + encodedValue(lastNameField) +
"&emailAddress=" + encodedValue(emailAddressField);
// Write POST data into local buffer
out.print(postData);
out.flush(); // Flush since above used print, not println
// POST requests are required to have Content-Length
String lengthString =
String.valueOf(byteStream.size());
connection.setRequestProperty
("Content-Length", lengthString);
// Netscape sets the Content-Type to multipart/form-data
// by default. So, if you want to send regular form data,
// you need to set it to
// application/x-www-form-urlencoded, which is the
// default for Internet Explorer. If you send
// serialized POST data with an ObjectOutputStream,
// the Content-Type is irrelevant, so you could
// omit this step.
connection.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// Write POST data to real output stream
byteStream.writeTo(connection.getOutputStream());
BufferedReader in =
new BufferedReader(new InputStreamReader
(connection.getInputStream()));
String line;
String linefeed = "n";
resultsArea.setText("");
while((line = in.readLine()) != null) {
resultsArea.append(line);
resultsArea.append(linefeed);
}
} catch(IOException ioe) {
// Print debug info in Java Console
System.out.println("IOException: " + ioe);
}
}
-- Stefan Deusch, August 29, 2000
--------------------------------------------------------------------------------
The textbook answer above worked fine, at least with the jdk1.2.2 appletviewer. However, I could not run it with the JVM of Netscape 4.7 or Internet Explorer on Win98. A more basic method opening a socket to port 80 and writing bytes (actually all that what class URLConnection wraps for you), I want to add here because someone asked me this already and I wasted 2 days trying to workaround a bad URLConnection class on Netscape and IE (for those of you writing Applets this is useful).
OutputStream out = null; DataInputStream in = null;
Socket s = null;
String postData = "key1=value&key2=value";
try {
s = new Socket(server, port);
out = s.getOutputStream();
// --- write your own HTTP-POST Header ----
String header = "POST " + servlet + " HTTP/1.0n"
+ "Content-type: application/x-www-form-urlencodedn"
+ "Content-length: " + postData.length()
+ "nn";
out.write(header.getBytes());
out.write(postData.getBytes());
out.flush();
// read answer if any
in = new DataInputStream(new
BufferedInputStream(s.getInputStream()));
. . .
-- Stefan Deusch, October 4, 2000
[...] for example, under the GET method, the browser might initiate the HTTP transaction as follows:
GET HTTP/1.0 /cgi-bin/guestbook.pl?firstname=Joe&lastname=Schmoe
[...] The POST method says to use the body portion of the HTTP request to pass parameters. The same transaction with the POST method would read as follows:
POST HTTP/1.0 /cgi-bin/guestbook.pl
... [More headers here]
firstname=Joe&lastname=Schmoe
-- from the Webmaster In a Nutshell, 1e (which you should pick up if you write web programs a lot.. it will explain other headers you will run across.. another great resource is the newly finalized (just about) HTTP/1.1 standard RFC--grab the HTTP/1.0 RFC too--they are both in plain English)
So basically.. when you create the string of text to send over your Java socket (or type over telnet): 1) you first make all your headers, line by line. 2) then add a blank line.. (e.g. nn) 3) and then add the parameters on the next line (without returns) however long the parameter may be. The parameters and url needs to be urlencoded (all non plain text "X" in the stream will be replaced with "%NN" hex equivalent) for older browsers and old webservers. It's the "safe" way. GET and POST is universal, regardless of what language you use. With Java however, you should read some Java network/applet programming FAQs downloadable from the web to understand some quirks involving socket usage from a wide variety of browser JVM.
-- Li-fan Chen, July 26, 2000
--------------------------------------------------------------------------------
An important point with the POST method is that it requires the content-length. The GET method does not, but it is limited to 300 or so bytes in length and should be reproducible (always yield the same result). The second important point is to specify the correct MIME-encoding for the filetype you want to upload.
Find java code online from the book Core Servlets and JavaServer Pages This method, taken from Chap.17, represents an actionhandler that can be assigned to a "Submit" button on your Applet.
public void actionPerformed(ActionEvent event) {
try {
String protocol = currentPage.getProtocol();
String host = hostField.getTextField().getText();
String portString = portField.getTextField().getText();
int port;
try {
port = Integer.parseInt(portString);
} catch(NumberFormatException nfe) {
port = -1; // I.e., default port of 80
}
String uri = uriField.getTextField().getText();
URL dataURL = new URL(/tech-qa-java/protocol, host, port, uri/index.html);
URLConnection connection = dataURL.openConnection();
// Make sure browser doesn't cache this URL.
connection.setUseCaches(false);
// Tell browser to allow me to send data to server.
connection.setDoOutput(true);
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512); // Grows if necessary
// Stream that writes into buffer
PrintWriter out = new PrintWriter(byteStream, true);
String postData =
"firstName=" + encodedValue(firstNameField) +
"&lastName=" + encodedValue(lastNameField) +
"&emailAddress=" + encodedValue(emailAddressField);
// Write POST data into local buffer
out.print(postData);
out.flush(); // Flush since above used print, not println
// POST requests are required to have Content-Length
String lengthString =
String.valueOf(byteStream.size());
connection.setRequestProperty
("Content-Length", lengthString);
// Netscape sets the Content-Type to multipart/form-data
// by default. So, if you want to send regular form data,
// you need to set it to
// application/x-www-form-urlencoded, which is the
// default for Internet Explorer. If you send
// serialized POST data with an ObjectOutputStream,
// the Content-Type is irrelevant, so you could
// omit this step.
connection.setRequestProperty
("Content-Type", "application/x-www-form-urlencoded");
// Write POST data to real output stream
byteStream.writeTo(connection.getOutputStream());
BufferedReader in =
new BufferedReader(new InputStreamReader
(connection.getInputStream()));
String line;
String linefeed = "n";
resultsArea.setText("");
while((line = in.readLine()) != null) {
resultsArea.append(line);
resultsArea.append(linefeed);
}
} catch(IOException ioe) {
// Print debug info in Java Console
System.out.println("IOException: " + ioe);
}
}
-- Stefan Deusch, August 29, 2000
--------------------------------------------------------------------------------
The textbook answer above worked fine, at least with the jdk1.2.2 appletviewer. However, I could not run it with the JVM of Netscape 4.7 or Internet Explorer on Win98. A more basic method opening a socket to port 80 and writing bytes (actually all that what class URLConnection wraps for you), I want to add here because someone asked me this already and I wasted 2 days trying to workaround a bad URLConnection class on Netscape and IE (for those of you writing Applets this is useful).
OutputStream out = null; DataInputStream in = null;
Socket s = null;
String postData = "key1=value&key2=value";
try {
s = new Socket(server, port);
out = s.getOutputStream();
// --- write your own HTTP-POST Header ----
String header = "POST " + servlet + " HTTP/1.0n"
+ "Content-type: application/x-www-form-urlencodedn"
+ "Content-length: " + postData.length()
+ "nn";
out.write(header.getBytes());
out.write(postData.getBytes());
out.flush();
// read answer if any
in = new DataInputStream(new
BufferedInputStream(s.getInputStream()));
. . .
-- Stefan Deusch, October 4, 2000
|
直接写的话,还是用get吧