简体   繁体   English

Http URL连接错误

[英]Http Url Connection error

I am getting the following error: 我收到以下错误:

java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=CONNECT_URL

Following are my Global variables: 以下是我的全局变量:

String CONNECT_URL = "http://api.openweathermap.org/data/2.5/weather?q=Mumbai";
    int LAST_INDEX; 
    String NAME; 
    String TYPE; 
    String GREETING_YEAR; 
    String GREETING_GENERAL; 
    String RADIO_TYPE;
    InputStream ins = null;
    String result = null; 

following is my parse function: 以下是我的解析函数:

public void parse(){
        DefaultHttpClient http = new DefaultHttpClient(new BasicHttpParams()); 
        System.out.println("URL is: "+CONNECT_URL); 
        HttpPost httppost = new HttpPost("CONNECT_URL");
        httppost.setHeader("Content-type", "application/json");
        try{
            HttpResponse resp = http.execute(httppost); 
            HttpEntity entity = resp.getEntity();
            ins = entity.getContent(); 
            BufferedReader bufread = new BufferedReader(new InputStreamReader(ins, "UTF-8"), 8); 
            StringBuilder sb = new StringBuilder(); 
            String line = null; 

            while((line = bufread.readLine()) != null){

                sb.append(line +"\n"); 

            }
            result = sb.toString(); 
            System.out.println("Result: "+result); 

        }catch (Exception e){
            System.out.println("Error: "+e);
        }finally{
            try{
                if(ins != null){
                    ins.close();
                }
            }catch(Exception squish){
                System.out.println("Squish: "+squish); 
            }
        }



    }

I tried to refator it with other similar questions on SO, but my URL seems to be okay and it returns the JSON once I check the same URL from a browser, any hints? 我尝试用SO上的其他类似问题来驳斥它,但是我的URL似乎还可以,并且一旦我从浏览器中检查了相同的URL,它就会返回JSON,是否有任何提示?

You´ve got 你有

HttpPost httppost = new HttpPost("CONNECT_URL");

and looking to your code should be like 并期待您的代码应该像

HttpPost httppost = new HttpPost(CONNECT_URL);

You are passing "CONNECT_URL" in HttpPost object which is wrong. 您正在HttpPost对象中传递“ CONNECT_URL”,这是错误的。 Use 采用

HttpPost httppost = new HttpPost(CONNECT_URL) //instead of HttpPost("CONNECT_URL")
HttpPost httppost = new HttpPost("CONNECT_URL");

should be 应该

HttpPost httppost = new HttpPost(CONNECT_URL);

As a side note, Java convention dictates that variables are camel case ( connectUrl ) and constants are uppercase ( CONNECT_URL ). 附带说明一下,Java约定规定变量为驼峰式( connectUrl ),常量为大写( CONNECT_URL )。

I think the problem comes from this line: 我认为问题出在这一行:

HttpPost httppost = new HttpPost("CONNECT_URL");

You are passing the string "CONNECT_URL" instead of passing the variable CONNECT_URL :) 您正在传递字符串"CONNECT_URL"而不是传递变量CONNECT_URL :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM