在webview中打开URL并解析它以显示图像

时间:2016-02-18 05:49:59

标签: android json android-intent webview

我想通过点击网址打开网页浏览。 Url提供json数据。如何在webview活动中解析此数据并显示图像?

我的网址是:http://a.nextput.com/api/single-offer/23/89533a6f4248873b08ce52ce680f29e7/a/fs

点击后我的json来自webview:

(function($, ng) {
    var $val = $.fn.val; // save original jQuery function
   // override jQuery function
  $.fn.val = function (value) {
    // if getter, just return original
    if (!arguments.length) {
      return $val.call(this);
    }
     // get result of original function
    var result = $val.call(this, value);
     // trigger angular input (this[0] is the DOM object)
    ng.element(this[0]).triggerHandler('input');
     // return the original result
    return result; 
  }
})(window.jQuery, window.angular);

我必须在webview中加载banner_url。请帮我解决一下。

3 个答案:

答案 0 :(得分:1)

只需像这样解析

JSONObject obj=new JSONObject(response);
JSONObject objOffer=obj.getJSONObject("offer");
String bannerUrl=objOffer.getString("banner_url");

你在这里获得了横幅网址。 现在只需在Webview中加载它。

WebSettings webSettings = wv.getSettings();
webSettings.setBuiltInZoomControls(true);
wv.loadUrl(bannerUrl);

答案 1 :(得分:0)

如果你想这样做:

1)从这个网址获取json

2)解析json并从中获取banner_url

3)在webview中显示该图像。

在这种情况下,首先使用HttpURLConnection从url获取json。写一个类似的函数:

public static String getJSON(String url) {
    HttpURLConnection connection = null;
    try {
        URL u = new URL(url);
        connection = (HttpURLConnection) u.openConnection();
        connection.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line).append("\n");
        }
        br.close();
        return sb.toString();

    } catch (ConnectException ex) {
        return ex.toString();
    } catch (Exception ex) {
        return ex.toString();
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception ex) {
                //disconnect error
            }
        }
    }
}

之后,解析json,然后执行

webView.loadUrl(banner_url);

请勿在网页视图中加载初始网址。那只是用于获取json。

答案 2 :(得分:0)

如评论中所述,我发给你代码:我使用了Retrofit Library来获取数据和解析:

在build.gradle中

  compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.squareup.retrofit:retrofit:1.9.0'

RetrotitActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;

import retrofit.Callback;
import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Path;

public class RetrofitAcitity extends AppCompatActivity {
    ImageView ivBanner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit_acitity);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ivBanner = (ImageView) findViewById(R.id.iv);
        callAPI(new String[]{"http://a.nextput.com/api/single-offer/23/", "89533a6f4248873b08ce52ce680f29e7/a/fs"});
    }


    public void callAPI(String[] url) {
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        RequestInterceptor requestInterceptor = new RequestInterceptor() {
            @Override
            public void intercept(RequestFacade request) {
                request.addHeader("Content-Type", "application/json");
            }
        };
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(url[0])
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setRequestInterceptor(requestInterceptor)
                .build();
        final GetAPI git = restAdapter.create(GetAPI.class);
        git.getData(url[1], new Callback<ResponseJson>() {
            @Override
            public void success(ResponseJson gitmodel, Response response) {

                if (gitmodel != null) {
                    if (gitmodel.getSuccess()) {
                        if (gitmodel.getOffer() != null) {
                            if (gitmodel.getOffer().getBannerUrl() != null) {
                                Picasso.with(RetrofitAcitity.this).load(gitmodel.getOffer().getBannerUrl()).into(ivBanner);
                            } else
                                Toast.makeText(RetrofitAcitity.this, "NO image Banner", Toast.LENGTH_SHORT).show();
                        }
                    }

                }
            }

            @Override
            public void failure(RetrofitError error) {
                Log.v("error", error.getKind().name());


            }
        });
    }


    public interface GetAPI {
        @GET("/{path}")
        public void getData(@Path(value = "path", encode = false) String path, Callback<ResponseJson> response);
    }

}

activity_retrofit_acitity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.ramesh.expandablelistview.RetrofitAcitity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <!--<include layout="@layout/content_retrofit_acitity" />-->

    <ImageView
        android:id="@+id/iv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/wallet_highlighted_text_holo_dark" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

ResponseJson.java

package com.ramesh.expandablelistview;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by Ramesh Kumar on 2/18/2016.
 */
//Generated From: http://www.jsonschema2pojo.org/
public class ResponseJson {

    @SerializedName("success")
    @Expose
    private Boolean success;
    @SerializedName("offer")
    @Expose
    private Offers offer;

    /**
     * @return The success
     */
    public Boolean getSuccess() {
        return success;
    }

    /**
     * @param success The success
     */
    public void setSuccess(Boolean success) {
        this.success = success;
    }

    /**
     * @return The offer
     */
    public Offers getOffer() {
        return offer;
    }

    /**
     * @param offer The offer
     */
    public void setOffer(Offers offer) {
        this.offer = offer;
    }

}

Offers.java

package com.ramesh.expandablelistview;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/**
 * Created by Ramesh Kumar on 2/18/2016.
 */

//Generated From: http://www.jsonschema2pojo.org/
public class Offers {

    @SerializedName("packageName")
    @Expose
    private String packageName;
    @SerializedName("campKey")
    @Expose
    private String campKey;
    @SerializedName("app_name")
    @Expose
    private String appName;
    @SerializedName("image_url")
    @Expose
    private String imageUrl;
    @SerializedName("desc1")
    @Expose
    private String desc1;
    @SerializedName("desc2")
    @Expose
    private Object desc2;
    @SerializedName("rdata")
    @Expose
    private String rdata;
    @SerializedName("cats")
    @Expose
    private String cats;
    @SerializedName("banner_url")
    @Expose
    private String bannerUrl;
    @SerializedName("click_url")
    @Expose
    private String clickUrl;
    @SerializedName("country")
    @Expose
    private String country;
    @SerializedName("payout")
    @Expose
    private Double payout;

    /**
     *
     * @return
     * The packageName
     */
    public String getPackageName() {
        return packageName;
    }

    /**
     *
     * @param packageName
     * The packageName
     */
    public void setPackageName(String packageName) {
        this.packageName = packageName;
    }

    /**
     *
     * @return
     * The campKey
     */
    public String getCampKey() {
        return campKey;
    }

    /**
     *
     * @param campKey
     * The campKey
     */
    public void setCampKey(String campKey) {
        this.campKey = campKey;
    }

    /**
     *
     * @return
     * The appName
     */
    public String getAppName() {
        return appName;
    }

    /**
     *
     * @param appName
     * The app_name
     */
    public void setAppName(String appName) {
        this.appName = appName;
    }

    /**
     *
     * @return
     * The imageUrl
     */
    public String getImageUrl() {
        return imageUrl;
    }

    /**
     *
     * @param imageUrl
     * The image_url
     */
    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;
    }

    /**
     *
     * @return
     * The desc1
     */
    public String getDesc1() {
        return desc1;
    }

    /**
     *
     * @param desc1
     * The desc1
     */
    public void setDesc1(String desc1) {
        this.desc1 = desc1;
    }

    /**
     *
     * @return
     * The desc2
     */
    public Object getDesc2() {
        return desc2;
    }

    /**
     *
     * @param desc2
     * The desc2
     */
    public void setDesc2(Object desc2) {
        this.desc2 = desc2;
    }

    /**
     *
     * @return
     * The rdata
     */
    public String getRdata() {
        return rdata;
    }

    /**
     *
     * @param rdata
     * The rdata
     */
    public void setRdata(String rdata) {
        this.rdata = rdata;
    }

    /**
     *
     * @return
     * The cats
     */
    public String getCats() {
        return cats;
    }

    /**
     *
     * @param cats
     * The cats
     */
    public void setCats(String cats) {
        this.cats = cats;
    }

    /**
     *
     * @return
     * The bannerUrl
     */
    public String getBannerUrl() {
        return bannerUrl;
    }

    /**
     *
     * @param bannerUrl
     * The banner_url
     */
    public void setBannerUrl(String bannerUrl) {
        this.bannerUrl = bannerUrl;
    }

    /**
     *
     * @return
     * The clickUrl
     */
    public String getClickUrl() {
        return clickUrl;
    }

    /**
     *
     * @param clickUrl
     * The click_url
     */
    public void setClickUrl(String clickUrl) {
        this.clickUrl = clickUrl;
    }

    /**
     *
     * @return
     * The country
     */
    public String getCountry() {
        return country;
    }

    /**
     *
     * @param country
     * The country
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     *
     * @return
     * The payout
     */
    public Double getPayout() {
        return payout;
    }

    /**
     *
     * @param payout
     * The payout
     */
    public void setPayout(Double payout) {
        this.payout = payout;
    }

}

我已经创建了活动并使用改造来调用服务,并使模型类GSon将解析它,我将获得图像。 如果它有帮助那么接受它。并随时问你是否理解不清楚。