HttpUrlConnection的返回流无法得到

suqianc 2015-07-22 07:45:00
今天想写一个以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();
就不在执行下一个语句,而是跳到系统的一个函数里面,没有抛出异常。
问题:为什么会出现这种情况,登陆网址可以用的。为什么不能得到输出流??
...全文
247 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
suqianc 2015-07-23
  • 打赏
  • 举报
回复
今天发现了问题,网络请求必须在子线程中完成。哎,疏忽了。
Hare_ 2015-07-23
  • 打赏
  • 举报
回复
日志打印的有啥异常信息
第一种方法 使用标准的JAVA接口 1 将用户名和密码等用Map泛型封装 再使用StringBuffer 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据用POST 打开输入和输出 获取上传信息 字节大小以及长度 设置请求体的类型是文本类型 获得输出 向服务器输出数据 获得服务器响应的结果和状态码 如果 返回码等于200 得到服务器返回的输入 将输入转换成指定编码的字符串并返回 就可以成功提交并得到服务器返回的信息 第二种方法 使用标准Apache接口 02 03 15 19 30 + 06 12 02 03 15 19 30 31 + 06 12 1 将用户名和密码等用Map泛型封装 再使用List<NameValuePair> list new ArrayList<NameValuePair> ; 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据用POST 打开输入和输出 获取上传信息 字节大小以及长度 设置请求体的类型是文本类型 获得输出 向服务器输出数据 获得服务器响应的结果和状态码 如果 返回码等于200 得到服务器返回的输入 将输入转换成指定编码的字符串并返回 就可以成功提交并得到服务器返回的信息">第一种方法 使用标准的JAVA接口 1 将用户名和密码等用Map泛型封装 再使用StringBuffer 转换成一串字符串 然后新建URL打开openConnection 得到 httpURLConnection 设置最长连接时间和setRequestMethod请求方法 用GET还是POST 提交数据用POST [更多]
package com.kwantler.YN_EW.service.impl; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; public class FilePhoto { /** * 从网络Url中下载文件 * * @param urlStr * @param fileName * @param savePath * @throws IOException */ public static void downLoadByUrl(String urlStr, String fileName, String savePath) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置超时间为3秒 conn.setConnectTimeout(5 * 1000); // 防止屏蔽程序抓取而返回403错误 conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); // 得到输入 InputStream inputStream = conn.getInputStream(); // 获取自己数组 byte[] getData = readInputStream(inputStream); // 文件保存位置 File saveDir = new File(savePath); if (!saveDir.exists()) { saveDir.mkdir(); } File file = new File(saveDir + File.separator + fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(getData); if (fos != null) { fos.close(); } if (inputStream != null) { inputStream.close(); } System.out.println("info:" + url + " download success"); } /** * 从输入中获取字节数组 * * @param inputStream * @return * @throws IOException */ public static byte[] readInputStream(InputStream inputStream) throws IOException { byte[] buffer = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.close(); return bos.toByteArray(); } public static void main(String[] args) { try { downLoadByUrl( "https://www.mybiosource.com/images/tds/protocol_samples/MBS700_Antibody_Set_Sandwich_ELISA_Protocol.pdf", "ELISA.pdf", "E:/upload/protocol"); } catch (Exception e) { // TODO: handle exception } } }

80,351

社区成员

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

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