这是java客户端类:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;public class HttpClientContext {
public static final String DEFAULT_CHARSET = "UTF-8";
private static final String METHOD_POST = "POST";
private static final String METHOD_GET = "GET"; private HttpClientContext() {
} /**
 * 执行HTTP POST请求。
 * 
 * @param url
 *            请求地址
 * @param params
 *            请求参数
 * @return 响应字符串
 * @throws IOException
 */
public static String executePost(String url, Map<String, String> params,
int connectTimeout, int readTimeout) throws IOException {
return executePost(url, params, DEFAULT_CHARSET, connectTimeout,
readTimeout);
} /**
 * 执行HTTP POST请求。
 * 
 * @param url
 *            请求地址
 * @param params
 *            请求参数
 * @param charset
 *            字符集,如UTF-8, GBK, GB2312
 * @return 响应字符串
 * @throws IOException
 */
public static String executePost(String url, Map<String, String> params,
String charset, int connectTimeout, int readTimeout)
throws IOException {
String ctype = "application/json;charset="+charset;
String query = buildRequestParams(params, charset);
// byte[] content = {};
// if (query != null) {
// content = query.getBytes(charset);
// }
return executePost(url, ctype, query, connectTimeout, readTimeout);
} /**
 * 执行HTTP POST请求。
 * 
 * @param url
 *            请求地址
 * @param ctype
 *            请求类型
 * @param content
 *            请求字节数组
 * @return 响应字符串
 * @throws IOException
 */
private static String executePost(String url, String ctype, String content,
int connectTimeout, int readTimeout) throws IOException {
HttpURLConnection conn = null;
OutputStreamWriter out=null;

String rsp = null;
try {
try {
conn = getConnection(new URL(url), METHOD_POST, ctype);
conn.setConnectTimeout(connectTimeout);
conn.setReadTimeout(readTimeout);

} catch (IOException e) {
Map<String, String> map = getParamsFromUrl(url);
throw e;
}
try {
// 读和写流都创建,写流必须在读流之前,并且写流先给服务器发消息,不然创建了读流后发送数据,服务器会收不到.
out=new OutputStreamWriter (conn.getOutputStream());
out.write(content);

int responseCode=conn.getResponseCode();
System.out.println(responseCode);
rsp = convertResponseAsString(conn);
} catch (IOException e) {
Map<String, String> map = getParamsFromUrl(url);
throw e;
} } finally {
if (out != null) {
out.close();
}
if (conn != null) {
conn.disconnect();
}
}
System.out.println("输出结果:" + rsp);
return rsp;
} /**
 * 执行HTTP GET请求。
 * 
 * @param url
 *            请求地址
 * @param params
 *            请求参数
 * @return 响应字符串
 * @throws IOException
 */
public static String executeGet(String url, Map<String, String> params)
throws IOException {
return executeGet(url, params, DEFAULT_CHARSET);
} /**
 * 执行HTTP GET请求。
 * 
 * @param url
 *            请求地址
 * @param params
 *            请求参数
 * @param charset
 *            字符集,如UTF-8, GBK, GB2312
 * @return 响应字符串
 * @throws IOException
 */
public static String executeGet(String url, Map<String, String> params,
String charset) throws IOException {
HttpURLConnection conn = null;
String rsp = null; try {
String ctype = "application/x-www-form-urlencoded;charset="
+ charset;
String query = buildRequestParams(params, charset);
try {
conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype);
} catch (IOException e) {
Map<String, String> map = getParamsFromUrl(url);
throw e;
} try {
rsp = convertResponseAsString(conn);
} catch (IOException e) {
Map<String, String> map = getParamsFromUrl(url);
throw e;
} } finally {
if (conn != null) {
conn.disconnect();
}
} System.out.println("输出结果:" + rsp);
return rsp;
} private static HttpURLConnection getConnection(URL url, String method,
String ctype) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true); conn.setUseCaches(false);

conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "android");
conn.setRequestProperty("Content-Type", ctype);
conn.setRequestProperty("Accept-Language", "zh-cn");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");  return conn;
} private static URL buildGetUrl(String strUrl, String query)
throws IOException {
URL url = new URL(strUrl);
if (AppUtils.isBlank(query)) {
return url;
} if (AppUtils.isBlank(url.getQuery())) {
if (strUrl.endsWith("?")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "?" + query;
}
} else {
if (strUrl.endsWith("&")) {
strUrl = strUrl + query;
} else {
strUrl = strUrl + "&" + query;
}
} return new URL(strUrl);
} public static String buildRequestParams(Map<String, String> params,
String charset) throws UnsupportedEncodingException {
if (params == null || params.isEmpty()) {
return null;
}

// 对参数进行排序
List<Map.Entry<String, String>> newParams = new ArrayList<Map.Entry<String, String>>(
params.entrySet());
Collections.sort(newParams,
new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1,
Map.Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
}); StringBuilder query = new StringBuilder();
boolean hasParam = false;
for (Map.Entry<String, String> entry : newParams) {
String name = entry.getKey();
String value = entry.getValue(); // 忽略参数名或参数值为空的参数
if (AppUtils.areNotEmpty(name, value)) {
if (hasParam) {
query.append("&");
} else {
hasParam = true;
}
//query.append(name).append("=").append(URLEncoder.encode(value, charset));
query.append(name).append("=").append(value);
}
}
return query.toString();
} // query.append(name).append("=").append(URLEncoder.encode(value, charset)); protected static String convertResponseAsString(HttpURLConnection conn)
throws IOException {
String charset = getResponseCharset(conn.getContentType()); InputStream es = conn.getErrorStream();
if (es == null) {
return convertStreamAsString(conn.getInputStream(), charset);
} else {
String msg = convertStreamAsString(es, charset);
if (AppUtils.isBlank(msg)) {
throw new IOException(conn.getResponseCode() + ":"
+ conn.getResponseMessage());
} else {
throw new IOException(msg);
}
}
} private static String convertStreamAsString(InputStream stream,
String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
stream, charset));
StringWriter writer = new StringWriter(); char[] chars = new char[256];
int count = 0;
while ((count = reader.read(chars)) > 0) {
writer.write(chars, 0, count);
} return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
} private static String getResponseCharset(String ctype) {
String charset = DEFAULT_CHARSET; if (!AppUtils.isBlank(ctype)) {
String[] params = ctype.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("charset")) {
String[] pair = param.split("=", 2);
if (pair.length == 2) {
if (!AppUtils.isBlank(pair[1])) {
charset = pair[1].trim();
}
}
break;
}
}
} return charset;
} /**
 * 使用默认的UTF-8字符集反编码请求参数值。
 * 
 * @param value
 *            参数值
 * @return 反编码后的参数值
 */
public static String decode(String value) {
return decode(value, DEFAULT_CHARSET);
} /**
 * 使用默认的UTF-8字符集编码请求参数值。
 * 
 * @param value
 *            参数值
 * @return 编码后的参数值
 */
public static String encode(String value) {
return encode(value, DEFAULT_CHARSET);
} /**
 * 使用指定的字符集反编码请求参数值。
 * 
 * @param value
 *            参数值
 * @param charset
 *            字符集
 * @return 反编码后的参数值
 */
public static String decode(String value, String charset) {
String result = null;
if (!AppUtils.isBlank(value)) {
try {
result = URLDecoder.decode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
} /**
 * 使用指定的字符集编码请求参数值。
 * 
 * @param value
 *            参数值
 * @param charset
 *            字符集
 * @return 编码后的参数值
 */
public static String encode(String value, String charset) {
String result = null;
if (!AppUtils.isBlank(value)) {
try {
result = URLEncoder.encode(value, charset);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return result;
} private static Map<String, String> getParamsFromUrl(String url) {
Map<String, String> map = null;
if (url != null && url.indexOf('?') != -1) {
map = splitUrlQuery(url.substring(url.indexOf('?') + 1));
}
if (map == null) {
map = new HashMap<String, String>();
}
return map;
}

解决方案 »

  1.   

    /**
     * 从URL中提取所有的参数。
     * 
     * @param query
     *            URL地址
     * @return 参数映射
     */
    public static Map<String, String> splitUrlQuery(String query) {
    Map<String, String> result = new HashMap<String, String>(); String[] pairs = query.split("&");
    if (pairs != null && pairs.length > 0) {
    for (String pair : pairs) {
    String[] param = pair.split("=", 2);
    if (param != null && param.length == 2) {
    result.put(param[0], param[1]);
    }
    }
    } return result;
    }}下面是调用代码:
    String url="http://127.0.0.1/HelloServer.svc/Hello";
    HashMap<String,String> mapData = new HashMap<String,String>();
    mapData.put("name", "ruijc");
    HttpClientContext.executePost(url, mapData, 100000, 100000);
      

  2.   

    1. (最后应该说的:)一般我做这种事情,都是用java的 HttpClient 组件。很好用。2. 想知道为什么不能POST到WCF这边,可以两边都DEBUG啊~代码都是你的。3. 装个 HttpAnalyzer,抓包看看~今天太晚了,明晚你没有搞定,我再开IDE。
      

  3.   


    我也用了HttpClient,但还是一样的问题,我再试试,还请帮个忙看看。谢谢了。
      

  4.   

    healer_kx,发现问题了, out=new OutputStreamWriter (conn.getOutputStream());
    out.write(content); 上面的代码out没有调用flush()我加上这一句后:out.flush()后,我用HttpAnalyzer抓包得到PostData数据为:name=ruijc但Response Content返回的信息是:<?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>请求错误</title>
        <style>BODY { color: #000000; background-color: white; font-family: Verdana; margin-left: 0px; margin-top: 0px; } #content { margin-left: 30px; font-size: .70em; padding-bottom: 2em; } A:link { color: #336699; font-weight: bold; text-decoration: underline; } A:visited { color: #6699cc; font-weight: bold; text-decoration: underline; } A:active { color: #336699; font-weight: bold; text-decoration: underline; } .heading1 { background-color: #003366; border-bottom: #336699 6px solid; color: #ffffff; font-family: Tahoma; font-size: 26px; font-weight: normal;margin: 0em 0em 10px -20px; padding-bottom: 8px; padding-left: 30px;padding-top: 16px;} pre { font-size:small; background-color: #e5e5cc; padding: 5px; font-family: Courier New; margin-top: 0px; border: 1px #f0f0e0 solid; white-space: pre-wrap; white-space: -pre-wrap; word-wrap: break-word; } table { border-collapse: collapse; border-spacing: 0px; font-family: Verdana;} table th { border-right: 2px white solid; border-bottom: 2px white solid; font-weight: bold; background-color: #cecf9c;} table td { border-right: 2px white solid; border-bottom: 2px white solid; background-color: #e5e5cc;}</style>
      </head>
      <body>
        <div id="content">
          <p class="heading1">请求错误</p>
          <p xmlns="">服务器处理请求时遇到错误。有关构造有效服务请求的内容,请参阅<a rel="help-page" href="http://localhost:7278/WorkFlowRestService.svc/help">服务帮助页</a>。</p>
        </div>
      </body>
    </html>这个错误让我不解,难道WCF REST不能接受java发送Post的Http协议请求么?
      

  5.   

    晚上的,白天公司没有.Net环境。
      

  6.   


    谢谢healer_kx,问题解决了,因为我POST的数据格式是application/json,但我发送时未对数据加引号'"',所以服务端把POST数据识别成URL编码来了,所以出错。谢谢了,100分全给你。
      

  7.   

    嗯,对,
    JSON标准格式是两端有“”的。
      

  8.   


    谢谢了,以前没玩过HttpAnalyzer,还是你介绍后我才想到抓包,我也不知道发送的包是什么样的格式,还是通过你的工具才看出问题来。
      

  9.   

    {"action":"login","password":"ssss","username":"sssss","ecode":"ssss"}
    我发送的是这样的格式 有问题吗 也是不可以post 发送post请求就会报405错误!!
    两端加""是什么意思 难得还要这样"{"action":"login","password":"ssss","username":"sssss","ecode":"ssss"}" 
    楼主能给知道下吗 我都纠结了好几天了 
      

  10.   

    为什么我把代码复制过来 AppUtils这个类没有 楼主能发我吗 [email protected]