【问题标题】:How to send data from an android app to html and receive info back?如何将数据从 android 应用程序发送到 html 并接收回信息?
【发布时间】:2014-07-11 18:40:11
【问题描述】:

我需要发送三条信息: 域、电子邮件和移动标识符。

我希望从网站上得到如下所示的 JSON 响应:

{
domain: example.com,
token: abcdefg123,
reportEmail: null,
mobileResultsPageUrl: http://completedtest.testingSite.com/mobile/abcdefg123/4a0ced51c00cfd5d6ce8b50d00be49f6
}

我最关心将在新活动中显示为 Web 视图的 Url。

这是我目前正在尝试的:

public void postData(){
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://exampleTestingSite.com/");

    try {
        // Add your data
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(3);
        pairs.add(new BasicNameValuePair("domain", "OswaldMagic.com"));
        pairs.add(new BasicNameValuePair("sendReportTo", "me@gmail.com"));
        pairs.add(new BasicNameValuePair("mobile", "1"));
        httppost.setEntity(new UrlEncodedFormEntity(pairs));

        // 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
    }
}

任何帮助将不胜感激。保重,早点说话, -斯蒂芬

【问题讨论】:

  • 您不能将数据发布到 html。好吧,你尝试了一些东西。你走了多远?请提供扩展报告。不要让我们猜测。
  • 我还没有走多远。你是说我们只能从网站获取数据?我们有没有办法将网站用作处理数据的工具?
  • 你想要的一切都是好的和可行的。有很多标准方法。你想要什么特别的。

标签: android webview http-post http-get


【解决方案1】:

它现在可以工作了!

我们必须让网站知道我们希望返回 JSON,因为默认设置为 HTML。我们通过修改 header 来接受 JSON 来做到这一点,见代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Accept", "application/json");

得到预期结果后,我只需要使用 JSON 的一部分。首先,我从网站上获取结果并将其转换为字符串:

resultHTML = Html.fromHtml(responseBody);

JSONObject obj = null;
try {
    obj = new JSONObject(String.valueOf(resultHTML));
} catch (JSONException e) {
    e.printStackTrace();
}
String resultsPageHTML = null;
try {
    resultsPageHTML = obj.getString("mobileResultsPageUrl");
} catch (JSONException e) {
    e.printStackTrace();
}

然后我调用了 sharedPreferences:

// create a file to save SharedPreferences in
public static final String PREFS_NAME = "MyPreferencesFile";
// call sharedPreferences
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
// call SharedPreferences editor
SharedPreferences.Editor editor = prefs.edit();
editor.putString("resultsPageHTML", resultsPageHTML);
editor.commit();

这样我就可以在另一个活动中收到它。

我希望这对正在经历类似斗争的人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2013-09-03
    • 2021-06-11
    • 2012-12-09
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多