package org.lambdasoft.http;
import java.util.Map;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public interface HttpRequest {
String execute(String url,Map<String, String> params) throws Exception;
}
package org.lambdasoft.http;
import java.util.Map;
import java.util.Set;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public class GetRequest implements HttpRequest{
@Override
public String execute(String url, Map<String, String> params) throws Exception {
HttpClient client = new HttpClient();
GetMethod getMethod = new GetMethod(url);
if(params != null && params.size() != 0) {
Set<String> keySet = params.keySet();
NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
int i = 0;
for (String key : keySet) {
nameValuePairs[i] = new NameValuePair(key, params.get(key));
i++;
}
getMethod.setQueryString(nameValuePairs);
}
int statusCode = client.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new Exception(getMethod.getStatusLine().toString());
}
return new String(getMethod.getResponseBody());
}
}
package org.lambdasoft.http;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
/**
* @author lei.tang (justinlei@gmail.com)
* @date
* @version
*/
public class PostRequest implements HttpRequest{
@Override
public String execute(String url, Map<String, String> params)
throws Exception {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
if(params != null && params.size() != 0) {
Set<String> keySet = params.keySet();
NameValuePair[] nameValuePairs = new NameValuePair[params.size()];
int i = 0;
for (String key : keySet) {
nameValuePairs[i] = new NameValuePair(key, params.get(key));
i++;
}
postMethod.setQueryString(nameValuePairs);
}
int statusCode = client.executeMethod(postMethod);
if (statusCode != HttpStatus.SC_OK) {
throw new Exception(postMethod.getStatusLine().toString());
}
return new String(postMethod.getResponseBody());
}
}
|