gpt4 book ai didi

java - 对字符串的 Android Web 请求

转载 作者:太空狗 更新时间:2023-10-29 16:23:45 25 4
gpt4 key购买 nike

我想从网页中收集文本,将其放入字符串中,然后在我的设备屏幕上显示。

这是我的 WebRequest Activity :

package com.work.webrequest;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WebRequest extends Activity {


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText(getPage());
}

private String getPage() {
String str = "***";

try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://zapmenow.co.uk/zapme/?getDetails=true&secret=zjXvwX5frK1po0adXyKJsbbyUe2ZY2PkW9M8r7sb1soIDppIWdTlgt1xmL5VM6g&UDID=401ceca29af68e4569a25e8c16a6987bb8cf1f5a&id=41");

HttpResponse rp = hc.execute(post);

if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}

return str;
}


}

主.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView1"
android:text=""
android:layout_width="wrap_content"></TextView>
</LinearLayout>

我在 Eclipse 中没有任何错误,但应用程序在我的设备上崩溃了。

PS: 我添加了这行

 <uses-permission android:name="android.permission.INTERNET" />

在 list 中,所以互联网权限不是问题。

最佳答案

这是对我有用的代码:

private String getPage(String url) {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.connect();

if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}

private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;

while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}

bufferedReader.close();
return stringBuilder.toString();
}

稍后,您可以通过以下方式使用它:

String response = getPage("http://example.com");

关于java - 对字符串的 Android Web 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7514828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com