【发布时间】:2018-09-04 10:08:04
【问题描述】:
我是 java 的新手,我在这里尝试做的是每次按下按钮时发送一个 Post 请求。这是我的代码
public class Remotetask extends AppCompatActivity {
TextView tv;
Button btn;
public void PostRequest(String url_from_text) throws IOException {
String url = url_from_text;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print in String
tv.setText(response.toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_eve_aioremote);
btn = (Button) findViewById(R.id.Button1);
tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) throws IOException{
PostRequest("api endpoint");
}
});
}
}
这里有这行
public void onClick(View v) 抛出 IOException
在这里给我这个错误:
错误:onClick(View) in 无法在 OnClickListener 中实现 onClick(View) 被覆盖的方法不会抛出 IOException
我发现另一个人问了一个类似问题的帖子,但答案真的没有帮助我,因为我对此有点陌生。谢谢你。
【问题讨论】:
-
抛出runtimeexeption而不是检查异常或直接在onCick方法中处理异常
-
我建议你使用 volley 或改造库而不是手动代码