码迷,mamicode.com
首页 > Web开发 > 详细

客户端通过http协议以多参数方式连接服务端

时间:2015-03-05 22:23:26      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

服务端:
/**
 * 接收并处理http请求
 */
public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String broadcast = request.getParameter("broadcast");
String username = request.getParameter("username");
String title = request.getParameter("title");
String message = request.getParameter("message");
String uri = request.getParameter("uri");
String apiKey = Config.getString("apiKey", "");
logger.debug("apiKey=" + apiKey);
if (broadcast.equalsIgnoreCase("Y")) {
notificationManager.sendBroadcast(apiKey, title, message, uri);
} else {
notificationManager.sendNotifcationToUser(apiKey, username, title, message, uri);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
return null;
}




客户端:
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class ClientTest {
/**
* 第一种方案
* 多参数以post方式提交
* */
public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception{  
       StringBuilder sb = new StringBuilder();  
        if(params!=null && !params.isEmpty()){  
            for(Map.Entry<String, String> entry : params.entrySet()){  
                sb.append(entry.getKey()).append(‘=‘)  
                    .append(URLEncoder.encode(entry.getValue(), enc)).append(‘&‘);  
            }  
            sb.deleteCharAt(sb.length()-1);  
        }  
        byte[] entitydata = sb.toString().getBytes();//得到实体的二进制数据  
        URL url = new URL(path);  
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
        conn.setRequestMethod("POST");  
        conn.setConnectTimeout(5 * 1000);  
        conn.setDoOutput(true);//如果通过post提交数据,必须设置允许对外输出数据  
        //Content-Type: application/x-www-form-urlencoded  
        //Content-Length: 38  
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
        conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));  
        OutputStream outStream = conn.getOutputStream();  
        outStream.write(entitydata);  
        outStream.flush();  
        outStream.close();  
        if(conn.getResponseCode()==200){  
            return true;  
        }  
        return false;  
    } 
/**
* 测试
* */
public void testSendPostRequest() throws Throwable{  
        Map<String, String> params = new HashMap<String, String>();  
        params.put("method", "save");  
        params.put("title", "smith赵虹荣");  
        params.put("timelength", "80");  
        new ClientTest().sendPostRequest("http://localhost:8080/msgServer.do", params, "UTF-8");  
    }

/**
* 第二种方案
* 多参数以post方式提交
* */
public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception{  
        List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();  
        if(params!=null && !params.isEmpty()){  
            for(Map.Entry<String, String> entry : params.entrySet()){  
                paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));  
            }  
        }  
        UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);//得到经过编码过后的实体数据  
        HttpPost post = new HttpPost(path); //form  
        post.setEntity(entitydata);  
        DefaultHttpClient client = new DefaultHttpClient(); //浏览器  
        HttpResponse response = client.execute(post);//执行请求  
        if(response.getStatusLine().getStatusCode()==200){  
            return true;  
        }  
        return false;  
    }  
/**
* 测试
* */
public void testSendRequestFromHttpClient() throws Throwable{  
   Map<String, String> params = new HashMap<String, String>();  
   params.put("method", "save");  
   params.put("title", "赵虹荣");  
   params.put("timelength", "80");  
   boolean result = new ClientTest().sendRequestFromHttpClient("http://localhost:8080/msgServer.do", params, "UTF-8");  
}    

public static void main(String[] args) throws Exception{
try {
new ClientTest().testSendPostRequest();
} catch (Throwable e) {
e.printStackTrace();
}
}
}

客户端通过http协议以多参数方式连接服务端

标签:

原文地址:http://blog.csdn.net/sprita1/article/details/44087621

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!