我的问题是,执行conn.connect();
时,我的应用崩溃了。
这是我的代码:
package com.example.andrejkovict.myapplication;
import ...
public class MainActivity extends AppCompatActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "localhost/test.php?tel="+number;
String ret = HttpGet(url);
Log.e("tag","http "+ret);
}
public String HttpGet(String myUrl) throws IOException
{
InputStream inputStream = null;
String result = "";
URL url = new URL(myUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
Log.e("tag","http 1");
conn.connect();
Log.e("tag","http 2");
inputStream = conn.getInputStream();
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
return result;
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException
{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null) result += line;
inputStream.close();
return result;
}
}
在控制台中,仅输出为:“ http 1”,而不是“ http 2”和“ http返回字符串”
哪里有问题?
感谢您的帮助。
答案 0 :(得分:0)
使用下面的代码。
String urlink = "http://localhost/test.php?tel="+number;
URL url = new URL(link);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String data = "";
String webPage="";
while ((data = reader.readLine()) != null) {
webPage += data + "\n";
}