如何用Java通过POST方法向HTTP接口传递数据
1个回答
展开全部
这是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();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询