---
title: "使用HttpURLConnection向服务器发送post和get请求"
author: "huttoncs"
date: "2014-07-24T13:39:34Z"
tags: []
categories: ["企业架构"]
slug: "httpurlconnection-post-get"
draft: false
lastmod: "2015-03-20T15:50:58Z"
id: 2095862
url: "https://huttoncs.iteye.com/blog/2095862"
---

//向服务器发送get请求

@Test  
    publicvoid sendSms() throws Exception{  
        String message="货已发到";  
        message=URLEncoder.encode(message, "UTF-8");  
        System.out.println(message);  
        String path ="[http://localhost:8083/DS\_Trade/mobile/sim!add.do?message="+message](http://localhost:8083/DS_Trade/mobile/sim!add.do?message=%22%20message);  
        URL url =new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setConnectTimeout(5\*1000);  
        conn.setRequestMethod("GET");

        conn.connect();  
        InputStream inStream = conn.getInputStream();     
        byte\[] data = StreamTool.readInputStream(inStream);  
        String result=new String(data, "UTF-8");  
        System.out.println(result);  
    }

 

2、从服务器读取数据    

```
String message=request.getParameter("message");
```

 

 

二、使用HttpURLConnection向服务器发送post请求

1、向服务器发送post请求

@Test  
    publicvoid addByUrl() throws Exception{  
        String encoding="UTF-8";  
        String params="\[{\\"addTime\\":\\"2011-09-19 14:23:02\\"\[],\\"iccid\\":\\"1111\\",\\"id\\":0,\\"imei\\":\\"2222\\",\\"imsi\\":\\"3333\\",\\"phoneType\\":\\"4444\\",\\"remark\\":\\"aaaa\\",\\"tel\\":\\"5555\\"}]";  
        String path ="[http://localhost:8083/xxxx/xxx/sim!add.do](http://localhost:8083/xxxx/xxx/sim!add.do)";  
        byte\[] data = params.getBytes(encoding);  
        URL url =new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setDoOutput(true);  
        //application/x-javascript text/xml-&gt;xml数据 application/x-javascript-&gt;json对象 application/x-www-form-urlencoded-&gt;表单数据  
        conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);  
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));  
        conn.setConnectTimeout(5\*1000);  
        OutputStream outStream = conn.getOutputStream();  
        outStream.write(data);  
        outStream.flush();  
        outStream.close();  
        System.out.println(conn.getResponseCode()); //响应代码 200表示成功  
        if(conn.getResponseCode()==200){  
            InputStream inStream = conn.getInputStream();    
            String result=new String(StreamTool.readInputStream(inStream), "UTF-8");  
        }  
    }

 

2、从服务器读取数据   

```
//获取post请求过来的数据
byte[] data=StreamTool.readInputStream(request.getInputStream());
        //[{\"addTime\":\"2011-09-19 14:23:02\"[],\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]  
      
String json=new String(data, "UTF-8");
```

 

 3、服务器端的响应处理

 

response.setContentType("application/octet-stream");//浏览器无法使用某种方式或激活某个程序来处理的MIME类型  
     
   ServletOutputStream os = response.getOutputStream();

 

String rsp = "User\_name=002&errcode=0&errmsg=测试";  
     
   os.write(rsp.getBytes("UTF-8"));

 

//下面的方式为处理 对象类型 的响应数据。

//BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);  
//   ObjectOutputStream objectOutputStream = new ObjectOutputStream(bufferedOutputStream);  
//     
//   objectOutputStream.writeObject(rsp);  
//   objectOutputStream.writeBytes(rsp);  
   os.flush();  
//   objectOutputStream.close();

 

 

 

ps:客户端对对象类型的解析方法

InputStream is = postMethod.getResponseBodyAsStream();

   /*  
    * BufferedReader br = new BufferedReader(new  
    * InputStreamReader(is));  
    *  
    * String objString = ""; String tempString = ""; while ((tempString =  
    * br.readLine()) != null) { objString += tempString; }  
    \*/  
   ObjectInputStream objectInputStream = new ObjectInputStream(new BufferedInputStream(is));

   response = (Response) objectInputStream.readObject();  
   objectInputStream.close();