JAVA HttpURLConnection请求异常

public String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = “”;
URL realUrl = null;
// URLConnection conn = null;
HttpURLConnection conn= null;
InputStream is = null;
try {
realUrl = new URL(url);
// 打开和URL之间的连接
conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty(“Accept”, “application/json”);
conn.setRequestProperty(“Content-Type”, “application/json;charset=UTF-8”);
conn.setRequestProperty(“Accept-Language”, “zh-cn”);
conn.setRequestMethod(“POST”);
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(60000);
conn.setReadTimeout(60000);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 获取响应码
int statusCode = conn.getResponseCode();

        if (statusCode != 200 && statusCode != 204) {
            // 重点:由于HttpURLConnection发送请求返回500错误,只有状态码,没有具体响应内容,需要调用getErrorStream获取具体响应内容;注意:HttpClient无此问题。
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), "utf-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
            reader.close();
        }else {
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        }

    } catch (Exception e) {


        System.out.println("发送 POST 请求出现异常!"+e.getMessage());
        e.printStackTrace();
        throw new ServiceException("发送 POST 请求出现异常");
    }
    //使用finally块来关闭输出流、输入流
    finally{
        try{
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }
    return result;
}
下载文本的类和方法 ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpDownload { //下载文本文件 public String download(String strurl){ StringBuffer sb=new StringBuffer(); String line=null; BufferedReader buffer=null; try{ URL url=new URL(strurl); HttpURLConnection conn=(HttpURLConnection)url.openConnection(); buffer=new BufferedReader(new InputStreamReader((conn.getInputStream()),"UTF-8")); 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(); } } ``` 在Activity中调用 ``` import android.app.ListActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.zhu.util.*; public class Mp8Activity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mp8); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.layout.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. if(item.getItemId()==R.id.about){ //关于 }else if(item.getItemId()==R.id.update){ //更新文件列表 String xml=downloader("http://127.0.0.1:8080/MP3/resurce.xml"); System.out.println("xml-->"+xml); } return super.onOptionsItemSelected(item); } private String downloader(String strurl){ HttpDownload http=new HttpDownload(); String result=http.download(strurl); return result; } } ``` 测试一下得到的结果是 xml--> 无法将文件中的内容输出出来
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页