public class HttpUtil {
private static String PATAH="http://112.83.242.73/http/HttpServlet";
private static URL url;
static {
try {
url=new URL(PATAH);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String sendPost(Map<String,String> params,String encode){
StringBuffer buffer=new StringBuffer();
try{
if(params!=null && !params.isEmpty()){
//拼接StringBuffer
for(Map.Entry<String, String> entry: params.entrySet()){
buffer.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(),encode))
.append("&");
}
}
buffer.deleteCharAt(buffer.length()-1);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setConnectTimeout(3000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
//获得上传的信息的字节大小,将StringBuffer变成字符串
byte[] mydata=buffer.toString().getBytes();
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(mydata.length));
//获得输出流,向服务输出数据
OutputStream outputStream=urlConnection.getOutputStream();
outputStream.write(mydata);
//状态码
int responseCode=urlConnection.getResponseCode();
if(responseCode==200){
return changInputStream(urlConnection.getInputStream(),encode);
}
}catch(Exception e){
e.printStackTrace();
}
return "";
}
private static String changInputStream(InputStream inputStream,String encode) {
//将输入流变成字符串
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[] data=new byte[1024];
int len=0;
String result="";
try{
if(inputStream!=null){
while((len=inputStream.read(data))!=-1){
byteArrayOutputStream.write(data,0,len);
}
}
result=new String(byteArrayOutputStream.toByteArray(),encode);
}catch(Exception e){
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, String>map=new HashMap<String, String>();
map.put("username", "rrr");
System.out.println(sendPost(map,"utf-8"));
}
}
Http的POST方式提交给服务器
最新推荐文章于 2025-06-11 13:06:20 发布