我是Android的新手,并试图实现谷歌API,但当我尝试将输入流从api转换为字符串时我得到空字符串我不知道我在哪里做错了。请帮忙。
我在按钮点击时调用Api的代码如下:
package com.mubu.wheathertoday.wheathertoday;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import javax.net.ssl.HttpsURLConnection;
public class WheatherActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wheather);
final String url1,url3;
url1="http://api.openweathermap.org/data/2.5/weather?q=";
url3="&mode=xml ";
final EditText etCity=(EditText)findViewById(R.id.etCity);
Button btnView=(Button)findViewById(R.id.btnViewWheather);
btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
List<Wheather> wheatherList=new ArrayList<Wheather>();
WheatherHandler wheatherHandler=new WheatherHandler();
String url2=etCity.getText().toString();
try {
URL url = new URL(url1+url2+url3);
//exception can raise Url must be https not http
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.connect();
InputStream is=conn.getInputStream();
String s= convertStreamToString(is);
etCity.setText(s);
// wheatherList=wheatherHandler.parse(is);
// for(Wheather weath:wheatherList)
// {
// etCity.setText(weath.getTemp()+weath.getCity()+weath.getSunRise());
// }
//
}
catch (Exception e)
{
// etCity.setText(e.getMessage());
}
}
});
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_wheather, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
这里我没有显示任何只是尝试将输入流转换为字符串并在编辑文本字段中显示字符串。我不知道我在哪里做错了。
答案 0 :(得分:0)
使用此代码:(将您的Uri传递给此方法并在AsyncTask中执行此操作或使用线程与Handler一起执行此操作)
public static String getData(String uri) {
BufferedReader reader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
答案 1 :(得分:0)
try {
HttpPost post = new HttpPost("http:// url.php");
post.setHeader("Content_Type", "application/x-www-form-urlencoded");
// post.setEntity(new UrlEncodedFormEntity(namevaluepair));
HttpClient clent = new DefaultHttpClient();
HttpResponse responce = clent.execute(post);
HttpEntity entity = responce.getEntity();
InputStream stream = entity.getContent();
InputStreamReader reader = new InputStreamReader(stream,
"iso-8859-1");
BufferedReader buffer = new BufferedReader(reader, 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = buffer.readLine()) != null) {
sb.append(line);
}
message = sb.toString();
} catch (Exception e) {
Ex = false;
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
答案 2 :(得分:0)
我尝试通过浏览器访问您在代码中使用的(HTTPS)网址,但无法访问该网址。我还检查了isitdownrightnow.com,似乎网站已关闭 - 这可能是从网址中获取数据的原因。 API的HTTP端点正在响应 - 也许你应该切换到HTTP端点?例如this call和this call都为我工作。
您是否尝试访问浏览器中的链接以排除网站已关闭?
编辑 - 我也支持其他人所说的内容:使用AsyncTask
或{{1}从主UI线程进行网络访问会更好}}
编辑2 - 对不起,您是对的,根据您的评论,您使用的是HTTP端点,但您使用Thread
的事实让我失望。在这种情况下,为什么不使用普通的HTTP连接?