Java 使用httpUrlConnection将数据发送到服务器
我正在尝试使用HTTP创建一个最简单的Web服务器和客户端。我应该使用同时使用两个连接的隧道方式;一个是接收数据的GET连接,另一个是发回数据的POST连接 下面是我的代码:Java 使用httpUrlConnection将数据发送到服务器,java,post,get,httpurlconnection,Java,Post,Get,Httpurlconnection,我正在尝试使用HTTP创建一个最简单的Web服务器和客户端。我应该使用同时使用两个连接的隧道方式;一个是接收数据的GET连接,另一个是发回数据的POST连接 下面是我的代码: //client GET Request setoURL(new URL("http://" + input.getIp() + ":" + input.getPort() + input.getUrlPath())); conn = (HttpURLConnection) geto
//client GET Request
setoURL(new URL("http://" + input.getIp() + ":" + input.getPort() + input.getUrlPath()));
conn = (HttpURLConnection) getoURL().openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5000);
conn.addRequestProperty("User-Agent", "VVTK (ver=40)");
conn.addRequestProperty("Accept", "application/x-vvtk-tunnelled");
conn.addRequestProperty("x-sessioncookie", uniqueId());
conn.addRequestProperty("Pragma", "no-cache");
conn.addRequestProperty("Cache-Control", "no-cache");
conn.setRequestProperty("Authorization",/*The Authorization*/);
conn.getResponseCode();
//Client POST request
HttpURLConnection second2 = (HttpURLConnection) apiCommand.getoURL().openConnection();
second2.setRequestMethod("POST");
second2.setReadTimeout(5000);
second2.setRequestProperty("User-Agent", "VVTK (ver=40)");
second2.setRequestProperty("x-sessioncookie", xsession);
second2.setRequestProperty("Pragma", "no-cache");
second2.setRequestProperty("Cache-Control", "no-cache");
second2.setRequestProperty("Content-Length", "7");
second2.setRequestProperty("Expires", "Sun, 9 Jan 1972 00:00:00 GMT");
second2.setRequestProperty("VerifyPassProxy", "yes");
second2.setRequestProperty("Authorization", /*The Authorization*/);
second2.setDoOutput(true);
reqStream = new DataOutputStream(second2.getOutputStream());
reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();
in = new BufferedReader(new InputStreamReader(second.getInputStream()));
String inputLine = "";
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
问题是post请求未发送。第一个连接((GET请求))将向我发送事件或所有响应。我不应该断开第二个连接或从第二个连接(POST请求)获取数据
问题:
为什么POST请求没有发送?之后
reqStream.writeBytes("Q2FuU2Vl");
reqStream.flush();
添加这一行
reqStream.close();
查看下面的代码。我通过GET或POST从java向php发送参数,通过POST发送文件。同时,数据将通过POST和GET两种方法发送。
Java代码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package httpcommunication;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/**
*
* @author me0x847206
*/
final public class HTTPCommunication {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
HTTPCommunication http = new HTTPCommunication("http://localhost/post/index.php");
http.addParam("data0", "0");
http.addParam("1");
http.addParam("", "2");
http.addFile( "", "txtFile.txt");
http.addFile( "", "photo2");
http.addFile( "photo3", "photo.png");
http.viaGET();
System.out.println("text = " + http.getLastResponse() );
}
HTTPCommunication(String url) {
this.url = url;
setFilePrefix("f_");
setParamPrefix("p_");
setEncoding("ISO-8859-1");
defaultFileName = 0;
defaultParamName = 0;
params = new java.util.TreeMap<>();
headers = new java.util.TreeMap<>();
files = new java.util.TreeMap<>();
}
public void viaPOST() {
send(POST_METHOD);
}
public void viaGET() {
send(GET_METHOD);
}
public void setURL(String s) {
url = s;
}
public boolean setEncoding(String s) {
if(!java.nio.charset.Charset.isSupported( s ))
return false;
urlEncoding = s;
return true;
}
public boolean setParamPrefix(String s) {
if( "".equals( s ) )
return false;
paramPrefix = s;
return true;
}
public boolean setFilePrefix(String s) {
if( "".equals( s ) )
return false;
filePrefix = s;
return true;
}
public String getURL() {
return url;
}
public String getEncoding() {
return urlEncoding;
}
public String getParamPrefix() {
return paramPrefix;
}
public String getFilePrefix() {
return filePrefix;
}
public String getLastResponse() {
return lastResponse.toString();
}
public int getLastResponseCode() {
return lastResponseCode;
}
public void addHeader(String key, String value) {
if("".equals( key ))
return;
if(headers.containsKey( key )) {
headers.remove( key );
}
headers.put( key, value);
}
public void addParam(String value) {
addParam("", value);
}
public void addParam(String key, String value) {
key = paramPrefix + ("".equals( key ) ? ("" + ++defaultParamName) : key);
if(params.containsKey( key )) {
params.remove( key );
}
params.put( key, value);
}
public void addFile(String path) {
addFile("", path);
}
public void addFile(String name, String path) {
name = filePrefix + ("".equals( name ) ? ("" + ++defaultFileName) : name);
if(files.containsKey( name )) {
files.remove( name );
}
files.put( name, path);
}
public void reset() {
headers.clear();
params.clear();
files.clear();
defaultParamName = 0;
defaultFileName = 0;
}
private void send(int type) {
try {
if( url.startsWith("https") )
return;
StringBuffer urlParams = new StringBuffer();
for(String s : params.keySet()) {
urlParams.
append("&").
append(URLEncoder.encode( s, urlEncoding)).
append("=").
append(URLEncoder.encode(params.get( s ) , urlEncoding));
}
System.out.println( urlParams + "" );
URL object = new URL(
url + (POST_METHOD == type ? "" : ("?" + urlParams))
);
HttpURLConnection connection = (HttpURLConnection) object.openConnection();
/*
with that line or without, is same effect
*/
//connection.setRequestMethod( POST_METHOD == type ? "POST" : "GET");
connection.setDoOutput( true );
connection.setDoInput( true );
connection.setUseCaches( false );
connection.connect();
for(String s : headers.keySet()) {
connection.setRequestProperty( s, headers.get( s ) );
}
try (DataOutputStream out = new DataOutputStream( connection.getOutputStream() )) {
if( POST_METHOD == type ) {
out.writeBytes( urlParams.toString() );
}
for(String name : files.keySet()) {
out.writeBytes( "&" + URLEncoder.encode( name, urlEncoding) + "=");
writeFile( out, files.get( name ) );
}
out.flush();
lastResponseCode = connection.getResponseCode();
try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
lastResponse = new StringBuffer();
while( null != (line = in.readLine()) ) {
lastResponse.append( line );
}
}
}
connection.disconnect();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
private void writeFile(final DataOutputStream out, final String path) {
try {
try (FileInputStream in = new FileInputStream(path)) {
byte bytes[] = new byte[4096];
int read, totalRead = 0;
while( -1 != (read = in.read(bytes)) ) {
out.writeBytes( URLEncoder.encode( new String( bytes, 0, read, urlEncoding ), urlEncoding) );
totalRead += read;
}
System.out.println("totalRead from " + path + " = " + totalRead + " (bytes).");
}
} catch (Exception e) {
System.out.println("Exception 2");
}
}
public static final int POST_METHOD = 0;
public static final int GET_METHOD = 1;
private String paramPrefix;
private String filePrefix;
private int defaultFileName, defaultParamName;
private final java.util.SortedMap<String, String> params;
private final java.util.SortedMap<String, String> headers;
private final java.util.SortedMap<String, String> files;
private String url = "";
private String urlEncoding;
private StringBuffer lastResponse = new StringBuffer();
private int lastResponseCode = 0;
}
/*
*要更改此许可证标题,请在“项目属性”中选择“许可证标题”。
*要更改此模板文件,请选择工具|模板
*然后在编辑器中打开模板。
*/
封装http通信;
导入java.io.BufferedReader;
导入java.io.DataOutputStream;
导入java.io.FileInputStream;
导入java.io.InputStreamReader;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
/**
*
*@author me0x847206
*/
最终公共类HTTPCommunication{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
HTTPCommunication http=新的HTTPCommunication(“http://localhost/post/index.php");
http.addParam(“数据0”、“0”);
http.addParam(“1”);
http.addParam(“,”2“);
http.addFile(“,”txtFile.txt”);
http.addFile(“,“photo2”);
http.addFile(“photo3”、“photo.png”);
http.viaGET();
System.out.println(“text=“+http.getLastResponse());
}
HTTPCommunication(字符串url){
this.url=url;
setFilePrefix(“f_513;”);
setParamPrefix(“p_”);
设置编码(“ISO-8859-1”);
defaultFileName=0;
defaultParamName=0;
params=newjava.util.TreeMap();
headers=newjava.util.TreeMap();
files=new java.util.TreeMap();
}
公共邮政({
发送(POST_方法);
}
公共无效viaGET(){
发送(获取方法);
}
公共void setURL(字符串s){
url=s;
}
公共布尔集合编码(字符串s){
如果(!java.nio.charset.charset.isSupported)
返回false;
url编码=s;
返回true;
}
公共布尔setParamPrefix(字符串s){
如果(“.”等于(s))
返回false;
参数前缀=s;
返回true;
}
公共布尔setFilePrefix(字符串s){
如果(“.”等于(s))
返回false;
filePrefix=s;
返回true;
}
公共字符串getURL(){
返回url;
}
公共字符串getEncoding(){
返回URL编码;
}
公共字符串getParamPrefix(){
返回参数前缀;
}
公共字符串getFilePrefix(){
返回文件前缀;
}
公共字符串getLastResponse(){
返回lastResponse.toString();
}
public int getLastResponseCode(){
返回最后的响应代码;
}
public void addHeader(字符串键、字符串值){
如果(“.”等于(键))
返回;
if(标题.容器(键)){
标题。删除(键);
}
headers.put(键、值);
}
公共void addParam(字符串值){
addParam(“”,值);
}
public void addParam(字符串键、字符串值){
key=paramPrefix+(“”.equals(key)?(“”+++defaultParamName):key);
if(参数containsKey(键)){
参数移除(键);
}
参数put(键、值);
}
公共void addFile(字符串路径){
addFile(“,路径);
}
公共void addFile(字符串名称、字符串路径){
name=filePrefix+(“”.equals(name)?(“”+++defaultFileName):name);
if(files.containsKey(name)){
文件。删除(名称);
}
文件.put(名称、路径);
}
公共无效重置(){
headers.clear();
参数clear();
clear()文件;
defaultParamName=0;
defaultFileName=0;
}
私有void发送(int类型){
试一试{
if(url.startsWith(“https”))
返回;
StringBuffer urlParams=新的StringBuffer();
对于(字符串s:params.keySet()){
urlParams。
追加(&”)。
追加(URLEncoder.encode(s,urlEncoding))。
附加(“=”)。
append(URLEncoder.encode(params.get,urlEncoding));
}
System.out.println(urlParams+“”);
URL对象=新URL(
url+(POST_方法==类型?”:(“?”+urlParams))
);
HttpURLConnection连接=(HttpURLConnection)对象。openConnection();
/*
不管有没有这条线,效果都一样
*/
//connection.setRequestMethod(POST_METHOD==类型?“POST”:“GET”);
connection.setDoOutput(真);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect();
对于(字符串s:headers.keySet()){
connection.setRequestProperty,headers.get;
}
try(DataOutputStream out=newdataoutputstream(connection.getOutputStream())){
if(POST_方法==类型){
out.writeBytes(urlParams.toString());
}
for(字符串名称:files.keySet()){
out.writeBytes(“&”+URLEncoder.encode(名称,URLEncodeding)+“=”);
writeFile(out,files.get(name));
}
out.flush();
lastResponseCode=connection.getResp
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
foreach($_POST as $key => $value) {
echo "<br \>\$_POST['$key'] ";
if( "f_" == substr( $key, 0, 2) ) {
echo " <= this is a file";
$file = fopen( $key, "wb");
fwrite( $file, $value );
fclose( $file );
} else {
echo " = $value";
}
}
foreach($_GET as $key => $value) {
echo "<br \>\$_GET['$key'] = $value";
}
?>
</body>
</html>
run:
&p_1=1&p_2=2&p_data0=0
totalRead from txtFile.txt = 3961 (bytes).
totalRead from photo2 = 17990 (bytes).
totalRead from photo.png = 56590 (bytes).
text = <!DOCTYPE html><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <br \>$_POST['f_1'] <= this is a file<br \>$_POST['f_2'] <= this is a file<br \>$_POST['f_photo3'] <= this is a file<br \>$_GET['p_1'] = 1<br \>$_GET['p_2'] = 2<br \>$_GET['p_data0'] = 0 </body></html>
BUILD SUCCESSFUL (total time: 1 second)