当前位置: 技术问答>java相关
如何用Java通过POST方法向HTTP接口传递数据?
来源: 互联网 发布时间:2015-07-29
本文导语: 我要用Java语言写通过POST方法向HTTP接口传递数据的程序,请问如何实现?就像在网页上按了“Submit”一样?谢谢! | 这是core java2的例子 URLConnection connection = url.openConnection();//url为http服务...
我要用Java语言写通过POST方法向HTTP接口传递数据的程序,请问如何实现?就像在网页上按了“Submit”一样?谢谢!
|
这是core java2的例子
URLConnection connection = url.openConnection();//url为http服务器地址
connection.setDoOutput(true);
PrintWriter out
= new PrintWriter(connection.getOutputStream());//获得输出流
//向服务器传递参数
Enumeration enum = nameValuePairs.keys();
while (enum.hasMoreElements())
{ String name = (String)enum.nextElement();
String value = nameValuePairs.getProperty(name);
char ch;
if (enum.hasMoreElements()) ch = '&'; else ch = 'n';
out.print(name + "="
+ URLEncoder.encode(value) + ch);
System.out.println(name+ value);
}
out.close();
//获取输入流
BufferedReader in;
try
{ in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
}
catch (FileNotFoundException exception)
{ InputStream err
= ((HttpURLConnection)connection).getErrorStream();
if (err == null) throw exception;
in = new BufferedReader(new InputStreamReader(err));
}
StringBuffer response = new StringBuffer();
String line;
//读取数据
while ((line = in.readLine()) != null)
response.append(line + "n");
in.close();
return response.toString();
}
}
URLConnection connection = url.openConnection();//url为http服务器地址
connection.setDoOutput(true);
PrintWriter out
= new PrintWriter(connection.getOutputStream());//获得输出流
//向服务器传递参数
Enumeration enum = nameValuePairs.keys();
while (enum.hasMoreElements())
{ String name = (String)enum.nextElement();
String value = nameValuePairs.getProperty(name);
char ch;
if (enum.hasMoreElements()) ch = '&'; else ch = 'n';
out.print(name + "="
+ URLEncoder.encode(value) + ch);
System.out.println(name+ value);
}
out.close();
//获取输入流
BufferedReader in;
try
{ in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
}
catch (FileNotFoundException exception)
{ InputStream err
= ((HttpURLConnection)connection).getErrorStream();
if (err == null) throw exception;
in = new BufferedReader(new InputStreamReader(err));
}
StringBuffer response = new StringBuffer();
String line;
//读取数据
while ((line = in.readLine()) != null)
response.append(line + "n");
in.close();
return response.toString();
}
}