如何用Java通过POST方法向HTTP接口传递数据?
展开全部
这是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();
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询