【问题标题】:Android HTTP Communication:Android HTTP 通信:
【发布时间】:2011-08-05 23:14:14
【问题描述】:

我创建了一个 android 应用程序,用于在服务器返回适当的答案之前将消息发送到服务器进行解释。我真的在尝试演示无线连接。

所以我只想从 Android 手机发送消息,什么是合适的方式.... httppost? (我已经使用缓冲区/打印对套接字进行了此操作)

在服务器类中我应该使用httpget来接收消息吗?

然后在消化消息并确定适当的结果后,我将如何将其发送回 android 应用程序?再次httppost?

从 android 应用程序读取它是否需要再次使用 httpget?

示例将不胜感激。请记住,我希望使用 http 协议!

亲切的问候

西蒙

【问题讨论】:

    标签: java android http


    【解决方案1】:

    我使用HttpClient 取得了不错的效果。

    (没有运行这个并省略了 try/catch,但它应该可以帮助你开始)。

    // setup the client
    HttpContext httpContext = new BasicHttpContext();
    DefaultHttpClient httpClient = new DefaultHttpClient();
    
    // setup the request
    HttpPost post = new HttpPost("http://someurl.com/");
    List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
    pairs.add(new BasicNameValuePair("name" , "value"));
    post.setEntity(new UrlEncodedFormEntity(pairs));
    
    // execute the request
    BasicHttpResponse response =
            (BasicHttpResponse)httpClient.execute(post, httpContext);
    
    // do something with the response
    InputStream is = response.getEntity().getContent();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    
    String content;
    StringBuilder contentBuilder = new StringBuilder();
    
    String line = null;
    while((line = br.readLine()) != null)
        contentBuilder.append(line);
    
    br.close();
    is.close();
    
    content = contentBuilder.toString();
    
    // done!
    

    【讨论】:

    • 另外你必须在你的 AndroidManifest.xml 中设置权限:
    【解决方案2】:

    HTTP POST 在这两种情况下都适用。您可以使用 java.net.HttpURLConnection 来执行 POST。

    这是一个很好的例子:http://www.rgagnon.com/javadetails/java-0084.html 通过这个答案链接到:Java: how to use UrlConnection to post request with authorization?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多