通过HTTP调用

时间:2016-06-01 21:12:06

标签: java android http parsing

我看到了一些帖子(比如这个帖子:Android HttpPost: how to get the result)但是这些答案的每个人现在都在2016年中期被推荐使用最新的Android并且不回答我的完整问题。

我让我的应用程序进行HTTP调用( http://52.35.9.101:8080/server/keeper/login_test.jsp?username=[uniquexx] ),如下所示:

new HttpRequest().execute("http://52.35.9.101:8080/server/keeper/login_test.jsp?username=[uniquexx]");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);

传递给名为HTTP request的异步java文件:

public class HttpRequest extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            responseString = out.toString();
            out.close();
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
    } catch (IOException e) {
        //TODO Handle problems..
    }
    return responseString;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Do anything with response..
}
}

如果您将此HTTP调用放入浏览器,您将看到服务器使用以下字符串进行响应(两个唯一的ID,由逗号分隔,我需要解析并保存到2个单独的变量中)

5467326,8674922

我的问题是如何将该输出保存到字符串中(我似乎在上面做),然后将该字符串解析为两个独立的变量(x&amp; y)。

修改 -----

@Override

protected void onPostExecute(String result) {
super.onPostExecute(result);
String x = null;
String y = null;
String[] resultItems = result.split(",");
Log.d("tag_name", "Result IS " +resultItems);
x = resultItems[0];
Log.d("tag_name", " XXXXX IS " +x);
y = resultItems[1];
Log.d("tag_name", " YYYYY IS " +y);

1 个答案:

答案 0 :(得分:0)

onPostExecute中 - 结果的值将是(在您的示例中),&#34; 5467326,8674922&#34; 如果一切顺利的话 - 在这种情况下。这是您分析和解析响应的方法

protected void onPostExecute(String result) {
    super.onPostExecute(result);
    //Do anything with response..
    String x = null;
    String y = null;
    String[] resultItems = result.split(",");
    x = resultItems[0];
    y = resultItems[1];
   //now do whatever with X and Y...

}

我希望这会对你有所帮助。