如何使用HttpUrlConnection从Servlet获取对Android的响应

如何使用HttpUrlConnection从Servlet获取对Android的响应,android,servlets,httpurlconnection,server-communication,Android,Servlets,Httpurlconnection,Server Communication,我试图从servlet获取数据,但失败了。我使用了HttpUrlConnection类,而不是HttpClient或HttpConnection和“get”方法。我找不出有什么问题。Android应用程序并没有失败,但他们无法从服务器获取任何json字符串。这里有android日志、servlet代码和android代码 我真的很想知道什么是SBSETING、SHIPSHILD和SmartBonding,并解决这个问题。 请帮帮我 12-31 15:01:16.279 26003-26625/c

我试图从servlet获取数据,但失败了。我使用了HttpUrlConnection类,而不是HttpClient或HttpConnection和“get”方法。我找不出有什么问题。Android应用程序并没有失败,但他们无法从服务器获取任何json字符串。这里有android日志、servlet代码和android代码

我真的很想知道什么是SBSETING、SHIPSHILD和SmartBonding,并解决这个问题。 请帮帮我

12-31 15:01:16.279 26003-26625/capston.stol.dangerousplace I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
12-31 15:01:16.279 26003-26625/capston.stol.dangerousplace I/System.out: (HTTPLog)-Static: isShipBuild true
12-31 15:01:16.279 26003-26625/capston.stol.dangerousplace I/System.out: (HTTPLog)-Thread-3535-332636781: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
12-31 15:01:16.279 26003-26625/capston.stol.dangerousplace I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
12-31 15:01:16.289 26003-26625/capston.stol.dangerousplace I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
这是Servlet代码

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class WarningInfoView
 */
@WebServlet("/warning/view")
public class WarningInfoView extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        double xGps = 37.869972;
        double yGps = 127.743389;
        try {
            ServletContext sc = this.getServletContext();
            Class.forName(sc.getInitParameter("driver"));

            conn = DriverManager.getConnection(
                    sc.getInitParameter("url"),
                    sc.getInitParameter("username"),
                    sc.getInitParameter("password"));
            stmt = conn.createStatement();
            xGps = Double.parseDouble(request.getParameter("xcoord"));
            yGps = Double.parseDouble(request.getParameter("ycoord"));
            rs = stmt.executeQuery("SELECT idx,w_count,xcoord,ycoord,title FROM warning_info"
                    + " WHERE (xcoord BETWEEN "
                                +(xGps-0.00447625)+" AND "+(xGps+0.00447625)+ ") AND (" //위도 +-500m
                               +"ycoord BETWEEN "
                                +(yGps-0.055329)+" AND "+(yGps+0.055329)+");"); //경도 +-500m
            JSONObject jsonMain = new JSONObject();
            JSONArray jArray = new JSONArray();

            while(rs.next()){
                JSONObject jObject = new JSONObject();

                int idx = rs.getInt("idx");
                int w_count = rs.getInt("w_count");
                double xcoord = rs.getDouble("xcoord");
                double ycoord = rs.getDouble("ycoord");
                String title = rs.getString("title");

                jObject.put("idx", idx);
                jObject.put("w_count",w_count);
                jObject.put("xcoord",xcoord);
                jObject.put("ycoord",ycoord);
                jObject.put("title",title);

                jArray.add(0,jObject);
            }
            jsonMain.put("List", jArray);

            System.out.println(jsonMain.toJSONString());
            String json = jsonMain.toJSONString();

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(json);


        }catch (Exception e) {
            throw new ServletException(e);
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
这是Android代码

    private class SndMyLocReqWarnInfoList extends AsyncTask<String, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(String... param){

        String lat = param[0];
        String lng = param[1];
        try {

            Log.e("latlng", lat + ", " + lng);

            Properties prop = new Properties();
            prop.setProperty("xcoord", lat);
            prop.setProperty("ycoord", lng);
            String encodedString = encodeString(prop);

            URL url = new URL(getString(R.string.MainURL) + getString(R.string.SndMyLocReqWarnInfoList) + encodedString);

            Log.e("URL", url + "");

            HttpURLConnection conn= (HttpURLConnection)url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setRequestProperty("Accept", "application/json");
            conn.setRequestMethod("GET");

            try {

                int responseCode = conn.getResponseCode();
                Log.e("respCode", responseCode+"");

                if(responseCode == HttpURLConnection.HTTP_OK){
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));

                    String line = "";
                    String res = "";
                    while((line == br.readLine()) == true){
                        res += line;
                    }

                    Log.e("result json:", res);

                    is.close();
                }

            } catch (Exception e){
                Log.e("getwilist ", "error");
                e.printStackTrace();
            }

            conn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

}

public static String encodeString(Properties params) {
    StringBuffer sb = new StringBuffer(256);
    Enumeration names = params.propertyNames();

    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        String value = params.getProperty(name);
        sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value) );

        if (names.hasMoreElements()) sb.append("&");
    }
    return sb.toString();

}
私有类SndMyLocReqWarnInfoList扩展了异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的Void doInBackground(字符串…参数){
字符串lat=param[0];
管柱lng=参数[1];
试一试{
Log.e(“latlng”、“lat+”、“+lng”);
Properties prop=新属性();
道具设置属性(“xcoord”,纬度);
产权设定财产(“ycoord”,液化天然气);
字符串编码字符串=编码字符串(prop);
URL URL=新URL(getString(R.string.MainURL)+getString(R.string.SndMyLocReqWarnInfoList)+encodedString);
Log.e(“URL”,URL+”);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.SETUSECHACHES(假);
conn.setDoInput(真);
conn.setRequestProperty(“接受”、“应用程序/json”);
conn.setRequestMethod(“GET”);
试一试{
int responseCode=conn.getResponseCode();
Log.e(“respCode”,responseCode+”);
if(responseCode==HttpURLConnection.HTTP\u确定){
InputStream is=conn.getInputStream();
BufferedReader br=新的BufferedReader(新的InputStreamReader(is));
字符串行=”;
字符串res=“”;
而((line==br.readLine())==true){
res+=直线;
}
Log.e(“结果json:”,res);
is.close();
}
}捕获(例外e){
Log.e(“getwilist”、“error”);
e、 printStackTrace();
}
连接断开();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
@凌驾
受保护的void onCancelled(){
super.onCancelled();
}
}
公共静态字符串encodeString(属性参数){
StringBuffer sb=新的StringBuffer(256);
枚举名称=params.propertyNames();
while(names.hasMoreElements()){
字符串名称=(字符串)名称.nextElement();
字符串值=params.getProperty(名称);
sb.append(urlcoder.encode(name)+“=”+urlcoder.encode(value));
如果(names.hasMoreElements())sb.append(&);
}
使某人返回字符串();
}
用于检查您是否得到了有效的响应。 我正在使用以下get-using httpuurlconnection。请在下面使用并检查它

public String sendGet(String apiUrl) {
    StringBuilder result = new StringBuilder();
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(apiUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        urlConnection.disconnect();
    }
    return result.toString();
}

“无法从服务器获取任何json字符串。”。那么字符串res包含什么呢?你应该告诉你的代码是如何流动的。{“列表”:[{“xcoord”:37.869972,“idx”:3,“title”:“sbpark1”,“ycoord”:127.743089,“w_count”:0},{“xcoord”:37.869072,“idx”:2,“title”:“sbsb”,“ycoord”:127.743389,“w_count”:0},{“xcoord”:37.869972,“idx”:1,“title”:“hello”,“ycoord”:127.743389,“w_count”:0}这是URL的响应值。这个异步任务将它们的位置发送到服务器并接收信息列表(xcoord、ycoord、title、idx、count)。那你为什么说你没有?哦不…谢谢你,很抱歉打扰你。。。问题是。。。在while循环中,我写了两个等于。。。愚蠢的
while((line==br.readLine())==true)
在第行旁边…感谢您的评论,但它仍然不起作用。如果在getResponseCode()之后使用getInputStream(),您认为会出现问题吗?