大家看看,使用HttpURlConnnection老是报400,这是怎么回事呢

小哈的秘密城堡 2015-12-11 01:47:39
这个项目用HttpClient请求就没有问题,一换HttpUrlConnection就报400,先贴HttpClient的代码

分全给了。只要能解决。
public String connectionOnline(String[] parameter, Object[] parameterValue,
String method,Context context) {
String result = "";
DefaultHttpClient client = null;
try {
String url = “http://ip:端口/AsyncTask.svc” //这里用的是C#的服务端
//DBOpenHelper db = new DBOpenHelper(context);
//String url=db.Address().toString();
HttpPost req = new HttpPost(url + "/" + method);
req.setHeader("Accept", "application/json");
req.setHeader("Content-type", "application/json");
// 设置连接参数

BasicHttpParams connParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(connParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(connParams, 20 * 1000);

JSONObject o = new JSONObject();
for (int i = 0; i < parameter.length; i++) {
o.put(parameter[i], parameterValue[i]);
}

StringEntity s = new StringEntity(o.toString(), "utf-8");
req.setEntity(s);

// 构建执行请求客户端实例
client = new DefaultHttpClient(connParams);

// 发送请求,接收响应
HttpResponse resp = client.execute(req);
int g = resp.getStatusLine().getStatusCode();
// 判断响应码是否为200
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 获取响应数据实体类
HttpEntity respEntity = resp.getEntity();
result = EntityUtils.toString(respEntity, "utf-8");
}

} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接
client.getConnectionManager().shutdown();

}
Log.i("a", result);
return result;

}

下面在贴贴我写的HttpUrlConnection
public String connectionResult(String[] parameter,Object[] parameterValue,
String method,Context context){
HttpURLConnection conn = null;
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
StringBuffer responseResult = new StringBuffer();
StringBuffer params = new StringBuffer();
String myparams="";
try {
String myurl = “http://ip:端口/AsyncTask.svc” //这里用的是C#的服务端
String newUrl = myurl + method;
URL url = new URL(newUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);
// 设置通用的请求属性
conn.setRequestProperty("accept", "application/json");
conn.setRequestProperty("connection", "Keep-Alive");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();

DataOutputStream out = new DataOutputStream(conn.getOutputStream());

if(parameter.length > 0){
for(int i=0;i<parameter.length;i++){
params.append(parameter[i]+"="+URLEncoder.encode(parameterValue[i].toString(), "utf-8")+"&");
}
if(params.lastIndexOf("&")>0){
myparams = params.substring(0,params.length()-1);
}
}
out.writeBytes(myparams.toString());
out.flush();
out.close();

// 根据ResponseCode判断连接是否成功
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
System.out.println("Not Success");
} else {
System.out.println("Success");
}
// 定义BufferedReader输入流来读取URL的ResponseData
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseResult.append(line);
System.out.println(line);
}
/* 关闭DataOutputStream */
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
conn.disconnect();
try {
if (printWriter != null) {
printWriter.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return responseResult.toString();
}

下面是错误类型:

求各位美女帅哥们看看。拜托了
...全文
244 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
问题经大神指点解决了, 贴上我C#服务端代码:
[OperationContract]
        [WebInvoke(
        Method = "POST",
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        UriTemplate = "GetUsers")]
        int GetUsers(string userName, string userPwd);
这里接收的是json数据,然而我发送数据的时候发送的是conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); 这里我改成了conn.setRequestProperty("Content-Type", "application/json"); 还有那个参数的形式,拼成json后以流发出就好了 修改后代码:
 DataOutputStream out = new DataOutputStream(conn.getOutputStream());   

            JSONObject o = new JSONObject();
			for (int i = 0; i < parameter.length; i++) {
				o.put(parameter[i], parameterValue[i]);
			}

			out.writeBytes(o.toString());
            out.flush();
            out.close();
Sero_T 2015-12-11
  • 打赏
  • 举报
回复
这个以前也遇到过类似的,好像是和服务端有关系。。。

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧