【问题标题】:POST request does not reach the serverPOST 请求未到达服务器
【发布时间】:2011-10-16 14:06:32
【问题描述】:

我正在尝试通过 POST 请求将数据从 Android 智能手机发送到 REST Web 服务。

客户端没有错误,但是如果我发送了数据,服务器端没有执行代码:

客户:

public void connect2server(View v) throws IOException {

    HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.108:8182");

try {
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
     nameValuePairs.add(new BasicNameValuePair("id", "12345"));
     nameValuePairs.add(new BasicNameValuePair("stringdata", "data"));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}

服务器端:

public class data_server extends ServerResource {

public static void main(String[] args) throws Exception {  
    // Create the HTTP server and listen on port 8182  
    new Server(Protocol.HTTP, 8182, data_server.class).start();  
}  

@Post  
public String toString1() throws IOException {  
    System.out.println(getRequestEntity().getText());
    return "ok";  
}  

}

这是如何引起的,我该如何解决?

【问题讨论】:

    标签: android http rest post restlet


    【解决方案1】:

    没有错误,因为您正在捕获错误并且什么都不做。

    尝试将以下内容添加到 catch 块中,您应该会看到 LogCat 输出中发生了什么。记得导入 Log 类

    Log.w("com.name.pkg", e);
    

    其中“com.name.pkg”只是一个标签,因此可以帮助您进行过滤。通常是程序的名称。

    另外,很常用的是用 Toast.makeText(...).show(); 发送祝酒词。使用 e.getMessage() 但我不喜欢这样做,所以我不推荐它。您最好将字符串传递回调用函数并允许它来做 toast。

    【讨论】:

    • 您不需要将您的网址设置为类似http://192.168.1.108:8182/toString
    猜你喜欢
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    • 2020-01-20
    • 2018-01-09
    • 2016-09-29
    相关资源
    最近更新 更多