2013-03-07 58 views
5

我想从远程服务器获得响应。这里是我的代码:在HttpGet的android java.lang.IllegalArgumentException

private static String baseRequestUrl = "http://www.pappico.ru/promo.php?action="; 

    @SuppressWarnings("deprecation") 
    public String executeRequest(String url) { 
     String res = ""; 
     HttpClient httpClient = new DefaultHttpClient(); 
     HttpResponse response;  

     try { 
      //url = URLEncoder.encode(url, "UTF-8"); 
      HttpGet httpGet = new HttpGet(url); 

      response = httpClient.execute(httpGet); 
      Log.d("MAPOFRUSSIA", response.getStatusLine().toString()); 

      HttpEntity entity = response.getEntity(); 

      if (entity != null) { 
       InputStream inStream = entity.getContent(); 
       res = streamToString(inStream); 

       inStream.close(); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return res; 
    } 

    public String registerUser(int userId, String userName) { 
     String res = ""; 
     String request = baseRequestUrl + "RegisterUser&params={\"userId\":" + 
       userId + ",\"userName\":\"" + userName + "\"}"; 

     res = executeRequest(request); 

     return res; 
    } 

而且我得到的线HttpGet httpGet = new HttpGet(url)以下异常:在指数59非法字符查询:http://www.pappico.ru/promo.php?action=RegisterUser&params= { “用户id”

java.lang.IllegalArgumentException异常: 1,“userName”:“ЮрийКлинских”}

'{'字符有什么问题?我已阅读有关此异常的一些帖子,并找到了解决方法,但这种方法会导致另一种情况例外:如果我uncommet线url = URLEncoder.encode(url, "UTF-8");它craches在行response = httpClient.execute(httpGet);这样的例外:

java.lang.IllegalStateException:目标主机必须不为空或在参数中设置。方案= NULL,主机= NULL,PATH = http://www.pappico.ru/promo.php?action=RegisterUser&params= { “用户id”:1, “username” 的: “Юрий+Клинских”}

不知道我应该怎么做,使之工作。任何帮助,将不胜感激:)

回答

7

你必须编码URL参数:

String request = baseRequestUrl + "RegisterUser&params=" +  
     java.net.URLEncoder.encode("{\"userId\":" + userId + ",\"userName\":\"" + userName + "\"}", "UTF-8"); 
+0

这样做并线响应获得例外android.os.NetworkOnMainThreadException = httpClient.execute(HTTPGET); ' – konunger 2013-03-07 11:22:49

+3

在我看来,这是我的错误 - 我正在从UI线程使用网络)) – konunger 2013-03-07 11:30:29

0

尝试:

public String registerUser(int userId, String userName) { 
     String res = ""; 

     String json = "{\"userId\":" + 
       userId + ",\"userName\":\"" + userName + "\"}"; 
     String encodedJson = URLEncoder.encode(json, "utf-8"); 

     String request = baseRequestUrl + "RegisterUser&params=" + encodedJson; 

     res = executeRequest(request); 
     return res; 
    } 

(这个编码在PARAMS = ...的网址片段),而比整个网址。你也可以看看上面提到的可能的duplicate


加成: 注意,JSON通常通过POST传输(而不是GET)。您可以使用诸如“Live Headers”之类的程序,并手动执行这些步骤(例如注册用户)以查看幕后发生了什么。在这种情况下,您将在实体正文中发送{..}信息。下面是一种方法 - HTTP POST using JSON in Java

另外,编写JSON的另一种方法(特别是当它变得更复杂时)是使用模型类,然后使用ObjectMapper(如Jackson)将其转换为字符串。因为你避免在你的字符串如\”格式化这是非常方便

下面是一些例子:JSON to Java Objects, best practice for modeling the json stream