网络请求

来源:互联网 发布:2017最火的中文编程 编辑:程序博客网 时间:2024/06/06 09:01
public class HttpUtil {

    public String getFromPost(String str){
        String dataString="";
        URL url;
        try {
            url = new URL("http://op.juhe.cn/onebox/news/query");
            HttpURLConnection connection=(HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod("POST");
            //创建连接
            connection.connect();
            
            OutputStream os=connection.getOutputStream();
            DataOutputStream dos=new DataOutputStream(os);
            StringBuffer buffer=new StringBuffer();
            buffer.append(str);
            dos.writeBytes(buffer.toString());
            dos.flush();
            dos.close();
            
            
            
            //获取服务器数据
            int responseCode = connection.getResponseCode();
            if(responseCode==200){
                InputStream inputStream = connection.getInputStream();
                BufferedReader br=new BufferedReader(new InputStreamReader(inputStream));
                StringBuffer buffer2=new StringBuffer();
                String s;
                while((s=br.readLine())!=null){
                    buffer2.append(s);
                }
                br.close();
                inputStream.close();
                return buffer2.toString();
            }
            
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
        
        
        return dataString;
    }
0 0
原创粉丝点击