httpget连接问题

时间:2014-04-04 11:47:15

标签: android http-get

我试图将带有GET的参数发送到脚本,但我收到此错误:

java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=http://www.myurl.com/~or/senddata.php?paramDevice={deviceInfo}&paramVersion={osversion}

这是我的代码:

String url = "http://www.myurl.com/~or/senddata.php?paramDevice={deviceInfo}&paramVersion={osversion}";
String encodedUrl = URLEncoder.encode(url,"UTF-8");
HttpClient httpclient = new DefaultHttpClient();
httpclient.execute(new HttpGet(encodedUrl));

我看到了这个例外的一些其他问题,但是所有这些问题都有类和复杂方法的非常大的答案,我只想要一个将这两个参数发送到脚本的简约httpget连接。我不能用这段代码来回答这些答案。

我的代码中出错了什么?

由于

2 个答案:

答案 0 :(得分:2)

您只需要对参数进行编码,而不是整个网址:

String url = "http://www.myurl.com/~or/senddata.php?paramDevice="+URLEncoder.encode("{deviceInfo}")+"&paramVersion="+URLEncoder.encode("{osversion}");
    try {
         HttpClient httpclient = new DefaultHttpClient();
         httpclient.execute(new HttpGet(url));

    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

答案 1 :(得分:0)

请在请求中指定主机。请执行以下操作:

URIBuilder builder = new URIBuilder();

builder.setHost("myhost.com").setPath("/views");

URI uri = builder.build();

HttpGet httpget = new HttpGet(uri);