【问题标题】:Post url from android to retrieve data从 android 发布 url 以检索数据
【发布时间】:2012-05-14 07:01:07
【问题描述】:

我有一个网址“http://184.82.158.234/~store/rest/system/connect.json”,并使用名为 poster 的 mozilla 插件发布此网址,以 json 形式返回数据 我想要的是从 android 发布这个 url 以获取 json 数据到 androids 视图中。

非常感谢任何帮助 谢谢

【问题讨论】:

    标签: java android android-intent


    【解决方案1】:
    public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://184.82.158.234/~store/rest/system/connect.json");
    
    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
    
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
    } 
    

    响应变量将包含您的 json 数据。

    【讨论】:

    • 兄弟我已经试过你的解决方案不工作谢谢回复
    • 你能告诉我你必须这样做吗 nameValuePairs.add(new BasicNameValuePair("id", "12345"));因为我的网址不带任何参数,它只返回没有任何参数的数据
    • 你不能解析 json 吗?你能详细解释一下你的问题吗
    • 如果链接不带任何参数,则无需添加任何名称值对
    • 我收到异常说 json 未解析,我只想获取我在 android 中的 url 返回的数据无法从中捕获数据:(
    【解决方案2】:

    这是一个函数,您可以使用它来将字符串发布到 URL。

    public String doHttpPost(final String fullUrl, final String body) {
    
            final URL url = new URL(fullUrl);
    
            final HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    
            // set the request mode as POST
            urlConnection.setRequestMethod("POST");
    
            urlConnection.setUseCaches(false);
            urlConnection.setDoOutput(true);
    
            urlConnection.setRequestProperty("Accept-charset", "utf-8");
            urlConnection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
    
            final DataOutputStream request = new DataOutputStream(urlConnection.getOutputStream());
    
            // write the body.
            request.writeBytes(body);
    
            // flush output buffer
            request.flush();
            request.close();
    
            // construct a read using input stream and charset.
            final InputStreamReader isr = new InputStreamReader(urlConnection.getInputStream(), CHARSET_UTF8);
            final BufferedReader in = new BufferedReader(isr);
    
            String inputLine;
            final StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                stringBuilder.append(inputLine).append("\n");
            }
    
            in.close();
            isr.close();
    
            urlConnection.disconnect();
    
            return stringBuilder.toString(); 
    }
    

    【讨论】:

      【解决方案3】:

      检查下面的代码:试试这个可能对你有帮助。

          ArrayList nameValuePairs1 = new ArrayList();
      
              nameValuePairs1.add(new BasicNameValuePair("user_id", "")); 
              nameValuePairs1.add(new BasicNameValuePair("product_id", "")); 
              nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));
      
              HttpClient httpclient = new DefaultHttpClient();
      
              HttpPost httppost = new HttpPost(URL);
      
              httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
      
              HttpResponse responce = httpclient.execute(httppost);
      
              HttpEntity entity = responce.getEntity();
      
              is = entity.getContent();
      
              BufferedReader bufr = new BufferedReader(new InputStreamReader(is1,"iso-8859-1"), 8);
      
              StringBuilder sb = new StringBuilder();
      
              sb.append(bufr.readLine() + "\n");
      
              String line = "0";
      
              while ((line = bufr.readLine()) != null)
      
              {
      
              sb.append(line + "\n");
      
              }
      
              is1.close();
      
              result = sb.toString();
      

      result 是一个 json 字符串。解析该 json 并显示在任何控件中。我在文本视图中显示了这一点,见下文。

      final MyProgressDialog progDailog = new MyProgressDialog(Cheking_Review.this);
              final Handler handler = new Handler() {
                  @Override
                  public void handleMessage(Message msg) {
                      if (Name.length() > 0 && Name != null) {
                          txtvenue.setText(Name);
                      } else {
                          txtvenue.setText(venue_name);
                      }
                  }
              };
      
              new Thread() {
      
                  public void run() {
                      try {
      
      // put your result here
                          JSONObject jObject = new JSONObject(result);
                          JSONObject menuObject = jObject.getJSONObject("response");
                          JSONObject venueObject = menuObject.getJSONObject("venue");
                          Name = venueObject.getString("name");
      
                          String id = venueObject.getString("id");
      
                          Log.d("--------name---------", Name);
                          Log.d("--------id---------", id);
      
                      } catch (Exception e) {
                      }
                      handler.sendEmptyMessage(0);
                      progDailog.dismiss();
                  }
              }.start();
      

      【讨论】:

      • 好的让我试试你能告诉我这是什么吗? codenameValuePairs1.add(new BasicNameValuePair("user_id", "")); nameValuePairs1.add(new BasicNameValuePair("product_id", "")); nameValuePairs1.add(new BasicNameValuePair("product_review",""+text));code 因为我得到了没有任何参数的响应
      • 这是您必须使用 url 发送的参数,例如; www.xyz.com?name=dhaval&product_id=1&product_review=4。这是 get 方法,但如果你想使用 post 方法,那么你必须在数组中传递数据,就像我使用 nameValuePairs1 数组在答案中写的一样。
      • this *05-14 17:35:50.541: E/AndroidRuntime(1216): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.post/com.post.PostActivity }: android.os.NetworkOnMainThreadException 这使我的应用程序崩溃,我不知道如何解决它帮助 plzzz
      • 您添加了互联网权限??或者把你所有的日志放在这里,这会给你错误。在您的 android 清单文件中添加这两个许可。
      猜你喜欢
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多