我正在尝试将来自 EditText 的信息发布到 url,然后在应用程序上显示来自 Web 服务器的信息。我尝试了几种不同的方法来做到这一点,但每次尝试都会收到不同的错误消息。
我认为这与我正在编写网址有关,但我不知道该放在哪里,有什么想法吗?
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.send_button);
final EditText post = (EditText) findViewById(R.id.edit);
button1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
System.out.println(executeHttpGetRequest("http://free.worldweatheronline.com/feed/weather.ashx?q="+ post.getText().toString() + "&format=json&num_of_days=2&key=9e87fcbce7114648121009"));
}
});
}
private static String executeHttpGetRequest(String desiredUrl) throws Exception
{
URL url = null;
BufferedReader reader = null;
StringBuilder stringBuilder;
try
{
url = new URL(desiredUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(15*1000);
connection.connect();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e)
{
e.printStackTrace();
throw e;
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}