我编写了以下代码来向服务器发送请求并从服务器获取响应。但是,当我运行以下代码它不适合我。我基于this link编写了这段代码。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity);
Button button = (Button)findViewById(R.id.bu1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
run();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}
}
});
}
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://127.0.0.1:8080/file.php")
.build();
Call call = client.newCall(request);
Response response = call.execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
String text = response.body().string();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
}
答案 0 :(得分:0)
通常错误是因为:
没有互联网许可
在UI线程中
您可以在logcat中确认。
解决方案:
<uses-permission android:name="android.permission.INTERNET" />
您必须在其他线程中运行或使用异步,如下所示:
public void run() {
Request request = new Request.Builder()
.url("http://127.0.0.1:8080/file.php")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.d("TAG", "Failed: " + e.getMessage());
}
@Override
public void onResponse(Response response) throws IOException {
Log.d("TAG", "OK: " + response.body().string());
}
}
}