我对Android很新,我喜欢将输入流从一个类转移到另一个类。 基本上,我试图将一个地理编码的位置发送到服务器,并将响应发送到另一个类进行解析。
这是我到目前为止针对httppost和输入流响应的一段代码:
Location1.java
private void updateWithNewLocation(Location location) {
if (location != null) {
double lat = location.getLatitude();
String lat1 = Double.toString(lat);
double lng = location.getLongitude();
String lng1 = Double.toString(lng);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://...");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair(“lat”,lat1)); nameValuePairs.add(new BasicNameValuePair(“lng”,lng1)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream is = response.getEntity().getContent();
BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20);
int current = 0;
while((current = bis.read()) != -1){
baf.append((byte)current);
}
这是我希望解析输入流的另一个类的片段......这个类中已经有一个输入流,我试图弄清楚如何用其他类中的其他流替换它。
parser1.java
//I already have an inputstream here and this is where I want to inject the other class inputstream
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// parse the feed
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement(); ...
非常感谢任何帮助。
答案 0 :(得分:0)
我认为这比Android问题更像Java
个问题。你不能只使用现有的updateWithNewLocation()
方法public
并返回InputStream
而不是void
吗?类似的东西:
Location1.java
public static InputStream updateWithNewLocation(Location location) {
InputStream result = null;
if (location != null) {
double lat = location.getLatitude();
String lat1 = Double.toString(lat);
double lng = location.getLongitude();
String lng1 = Double.toString(lng);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://...");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("lat", lat1));
nameValuePairs.add(new BasicNameValuePair("lng", lng1));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
result = response.getEntity().getContent();
} catch(Exception e) {
//error handling
}
return result;
}
parser1.java
...
InputStream in = Location1.updateWithNewLocation(location)
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
// parse the feed
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
...