convertBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String text2 = editText2.getText().toString(); String apiUrl = "https://yurl6.cn/user/api.php"; String curl = "curl=" + text2; OkHttpClient client = new OkHttpClient(); MediaType mediaType = MediaType.parse("application/json"); RequestBody requestBody = RequestBody.create(mediaType, "{\"curl\":\"" + curl + "\"}"); Request request = new Request.Builder() .url(apiUrl) .post(requestBody) .build(); try { Response response = client.newCall(request).execute(); String result = response.body().string(); JSONObject jsonObject = new JSONObject(result); String shortUrl = jsonObject.getString("shortUrl"); editText3.setText(shortUrl); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }); } 在点击按钮后,app闪退
时间: 2023-12-03 15:02:53 浏览: 178
Android技术总结.doc
闪退可能是由于一些异常情况引起的,例如网络连接异常或JSON解析错误等。你可以在捕获异常的代码块中打印出异常信息来调试代码。请尝试以下修改,看看是否能够解决问题:
```java
convertBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String text2 = editText2.getText().toString();
String apiUrl = "https://yurl6.cn/user/api.php";
String curl = "curl=" + text2;
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody requestBody = RequestBody.create(mediaType, "{\"curl\":\"" + curl + "\"}");
Request request = new Request.Builder()
.url(apiUrl)
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
String result = response.body().string();
JSONObject jsonObject = new JSONObject(result);
String shortUrl = jsonObject.getString("shortUrl");
editText3.setText(shortUrl);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
```
同时,请确保你已经在Manifest.xml中声明了网络权限:
```xml
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文