我正在尝试创建一个按钮,该按钮使用android studio将HTTP请求发送到IP地址。我已经进行了研究,并使用异步方法进行了研究,但是由于某些原因,在使用.connect()函数后始终会出现错误,这意味着我无法进行连接。
我在清单上添加了INTERNET权限。
public class MainActivity extends AppCompatActivity {
Button btn;
TextView txtResponse;
RequestQueue queue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
queue = Volley.newRequestQueue(this);
btn.setTag(1);
btn.setText("ON");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
btn.setText("OFF");
v.setTag(0); //pause
} else {
btn.setText("ON");
v.setTag(1); //pause
}
final String url = "http://google.com";
String my_url = url;// Replace this with your own url
String my_data = "";// Replace this with your data
new MyHttpRequestTask().execute(my_url,my_data);
}
});
}
private class MyHttpRequestTask extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... params) {
String my_url = params[0];
String my_data = params[1];
String response = "";
response = ServiceHandler.findJSONFromUrl(my_url);
Log.d("rofl",response.toString());
return response;
}
}
}
class ServiceHandler {
// Create Http connection And find Json
public static String findJSONFromUrl(String url) {
String result = "";
try {
URL urls = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urls.openConnection();
conn.setReadTimeout(150000); //milliseconds
conn.setConnectTimeout(15000); // milliseconds
conn.setRequestMethod("GET");
conn.connect();//this is where it stops
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
conn.getInputStream(), "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} else {
return "error";
}
} catch (Exception e) {
// System.out.println("exception in jsonparser class ........");
e.printStackTrace();
return "error";
}
return result;
} // method ends
}
我正在使用Log.d将结果打印到日志中,但它始终会打印错误。我已经调试了代码,并且在调用.connect函数之后它停止了。