HttpUrlConnection的返回流无法得到

suqianc suqianc 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
今天想写一个以POST形式发送网络请求的登陆功能,具体代码如下:
定义函数:
public static String sendPostRequest(URL url,Map<String,String> pamas,String encode){
StringBuilder stringBuilder=new StringBuilder();
HttpURLConnection connection = null;
if(pamas!=null&&pamas.size()!=0)
{
for (Map.Entry<String,String> entry:pamas.entrySet()){
try {
stringBuilder.append(entry.getKey())
.append("=")
.append(URLEncoder.encode(entry.getValue(),encode))
.append("&");
}catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
}
stringBuilder.deleteCharAt(stringBuilder.length()-1);
try {
connection=(HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOutput(true);
//发送数据的大小
byte[] data=stringBuilder.toString().getBytes();
connection.setRequestProperty("Content_type","application/x-www-form-urlencoded");
connection.setRequestProperty("Content_length", String.valueOf(data.length));
connection.setUseCaches(false);

OutputStream outputStream=connection.getOutputStream();//这一句会使得程序崩溃,但没有 抛 出异常。
outputStream.write(data, 0, data.length);
outputStream.close();

int responseCode=connection.getResponseCode();
if(responseCode==200)
{
return changeInputStream(connection.getInputStream(),
encode);
}
}catch (IOException e){
e.printStackTrace();
}
return "";
}

public static String changeInputStream(InputStream in, String encode){
//内存流
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[] data=new byte[1024];
int length=0;
String result=null;
if(in!=null){
try {
while ((length=in.read(data))!=-1)
{
byteArrayOutputStream.write(data,0,length);
}
result=new String( byteArrayOutputStream.toByteArray(),encode);
}catch (IOException e){
e.printStackTrace();
}
}
return result;
}

在活动中写入如下代码:

String result;
Map<String,String> map=new HashMap<String,String>();
String username=user.getText().toString();
String passwords=password.getText().toString();
map.put("j_password", passwords);
map.put("j_username",username);
String address="http://120.26.83.51:8080/maya/demo/user/login";
try {
URL url=new URL(address);
result=HttpUtil.sendPostRequest(url,map,"utf-8");
Toast.makeText(this,result,Toast.LENGTH_LONG).show();

}catch (IOException e){
e.printStackTrace();
}

运行程序,直接崩溃!调试程序,发现走到
OutputStream outputStream=connection.getOutputStream();
就不在执行下一个语句,而是跳到系统的一个函数里面,没有抛出异常。
问题:为什么会出现这种情况,登陆网址可以用的。为什么不能得到输出流??
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
suqianc
Android 80,490 成员 91,371 内容