gpt4 book ai didi

java - 在 Android 中无法 http 连接

转载 作者:行者123 更新时间:2023-11-29 21:56:57 24 4
gpt4 key购买 nike

这段代码在 Java 中运行良好,但是当我开始在 Android 4.0 模拟器上运行它时它崩溃了。在调试时我注意到它在 httpConn.connect() 上崩溃了;行

  public class GetStringFromUrl {
public static String getString(String urlPageAdress) throws Exception
{

URL url = new URL(urlPageAdress);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestProperty("Accept-Encoding", "UTF-8");
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.connect(); //crashes on this line dunno know why

InputStream in = null;

if (httpConn.getContentEncoding() != null && httpConn.getContentEncoding().toString().contains("gzip")) {
in = new GZIPInputStream(httpConn.getInputStream());
} else {
in = httpConn.getInputStream();
}
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayBuffer baf = new ByteArrayBuffer(1000);
int read = 0;
int bufSize = 1024;
byte[] buffer = new byte[bufSize];
while (true) {
read = bis.read(buffer);
if (read == -1) {
break;
}
baf.append(buffer, 0, read);



}
String body = new String(baf.toByteArray());
return body;
} }

方法在主 Activity 中使用

公共(public)类 MainActivity 扩展 Activity{

ToggleButton  toogleButton;
public final static String EXTRA_MESSAGE = "ru.kazartsevaa.table.MESSAGE";
int upDown;
int SpinnerCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upDown=0;


setContentView(R.layout.activity_main);
}

public void onClick(View v) 抛出异常 { System.out.print(SpinnerCount); //if(upDown==0)//0 - вылет 1 прилет //{ 开关(v.getId()) { 案例 R.id.UpDownButton: { //toogleButton = (ToggleButton) findViewById(R.id.UpDownButton); //toogleButton.setOnCheckedChangeListener(this); } 案例 R.id.SheremetievoButton: { 旋转器 SherSpinner = (Spinner) findViewById(R.id.SheremetievoSpinner);

                    String SpinnerCount= SherSpinner.getItemAtPosition(SherSpinner.getSelectedItemPosition()).toString();
System.out.print(SpinnerCount);
new Thread(){ public void run() {
try {
String body = GetStringFromUrl.getString("www.xyz.com");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }.start();

int crowd;






}

}

注意:换到新线程后,它停止了粉碎,但仍然写入

最佳答案

您是在主线程中执行此操作吗?如果您在单独的线程中执行此操作,应该可以工作。

    public void onClick(View v) {
try{
new Thread(){
public void run() {
GetStringFromUrl.getString("www.xyz.com");
}
}.start();
}catch(Exception e){
e.printStackTrace();
}
}

关于java - 在 Android 中无法 http 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12999265/

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