HttpURlConnection.getResponseCode()为什么请求不成功?请大师指点一下。

xiaoaishuaige xiaoaishuaige 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
本人菜鸟自学android,遇到这个问题不知道怎么解决,还望高手指点一下。谢谢!(有些专业术语,不是很懂,所以问问题的时候写的有点。。。还望谅解)。
1.想实现的效果:通过URL,使用HttpURLConnection进行请求/响应,访问web服务器资源。
2.web Server:自己电脑安装的Tomcat 6.0
代码:

① DownloadActivity:
package mars.download;

import mars.utils.HttpDownloader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;;

public class DownloadActivity extends Activity {
/** Called when the activity is first created. */

private Button downloadTextButton;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
downloadTextButton=(Button) findViewById(R.id.textButton);
downloadTextButton.setOnClickListener(new DownloadTextListener());
}

class DownloadTextListener implements OnClickListener{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("!!!!!!!!!!!");
HttpDownloader httpdownloader=new HttpDownloader();
String test=httpdownloader.download("http://127.0.0.1:8080/test/cs.txt",3);
System.out.println(test);
}
}
}
②HttpDownloader(封装的一个下载类)
package mars.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

public class HttpDownloader {

private URL url=null;

@SuppressWarnings("finally")
public String download(String urlStr,int timeout){
StringBuffer sb=new StringBuffer();
String line=null;
BufferedReader buffer=null;
try{
//创建一个URL对象
url=new URL(urlStr);
//创建一个Http连接
HttpURLConnection urlcon=(HttpURLConnection) url.openConnection();
urlcon.setConnectTimeout(timeout*1000);
urlcon.connect();
int state=urlcon.getResponseCode();
System.out.println(state);
//判断请求是否成功
if(state==urlcon.HTTP_OK){
InputStream is=urlcon.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
buffer=new BufferedReader(isr);
while((line=buffer.readLine())!=null){
sb.append(line);
}
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
buffer.close();
}catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}
}
}
我直接用浏览器可以查看http://127.0.0.1:8080/test/cs.txt 文本信息。
/////////////////////////////以上只是部分代码,请大师帮我看一下,到底怎么回事。
真心想拜一位高手为师!我的联系方式:小艾 Q:365001126
...全文
评论 14
收藏 已收藏
分享
返回顶部
xiaoaishuaige
Web 开发 81,108 成员 341,721 内容