httpclient post提交报java.net.UnknownHostException

23 篇文章 0 订阅
我做了个简单的httpclient post 提交

不知为何总报java.net.UnknownHostException异常。


        url="http://www.dianpin.com";
        CityDetails citys = new CityDetails();
        // String targetRequest=citys.getCityDetails();
        String targetRequest = "aaa";
        HttpClient httpClient = new HttpClient();
        httpClient.getHostConfiguration().setHost(url);
        // 创建POST方法的实例
        PostMethod postMethod = new PostMethod();
        // 使用系统提供的默认的恢复策略
        postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler());
        postMethod.setRequestHeader( "User-Agent", "fake"); 
        // 填入各个表单域的值
        NameValuePair[] data = { new NameValuePair("request", targetRequest) };
        // 将表单的值放入postMethod中
        postMethod.setRequestBody(data);
        try {
            // 执行postMethod
            int statusCode = httpClient.executeMethod(postMethod);
            // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
            // 301或者302
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                    || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
                // 从头中取出转向的地址
                Header locationHeader = postMethod
                        .getResponseHeader("location");
                String location = null;
                if (locationHeader != null) {
                    location = locationHeader.getValue();
                    System.out
                            .println("The page was redirected to:" + location);

                } else {
                    System.err.println("Location field value is null.");
                }

            }
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "
                        + postMethod.getStatusLine());
            }
            // 读取内容
            byte[] responseBody = postMethod.getResponseBody();
            // 处理内容
            String str = new String(responseBody);
            //writeXML(str);
            System.out.println(str);

        } catch (HttpException e) {
            // 发生致命的异常,可能是协议不对或者返回的内容有问题
            System.out.println("Please check your provided http address!");
            e.printStackTrace();
        } catch (IOException e) {
            // 发生网络异常
            e.printStackTrace();
        } finally {
            // 释放连接
            postMethod.releaseConnection();
        }
    }

url换成我自己localhost:8081/ssh2/hello.action
也不行,但是在ie里面输入这个地址是可以运行的。
请问,这个问题如何解决,是由什么原因造成的?


我把代码改了下,
HttpClient httpClient = new HttpClient();
 // 创建POST方法的实例
  PostMethod postMethod = new PostMethod(url);
就可以了


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值