Java 应用程序在 getOutputStream() 处终止

标签 java android outputstream

我正在为我们的 Android 设备创建一个应用程序。本节的目的是将用户名和密码(当前仅分配为字符串)发布到 Web 服务并接收登录 token 。当运行代码时,在 getOutputStream() 行,我的代码终止并且不会再继续。

我已经为 Android 模拟器分配了 GSM 访问权限,并在 Eclipse 中设置了代理和 DNS 服务器。我现在不知道该去哪里!

这是在我的 onHandleIntent() 内:

protected void onHandleIntent(Intent i) {
    try{

        HttpURLConnection http_conn = (HttpURLConnection) new URL("http://www.XXXXX.com").openConnection();

        http_conn.setRequestMethod("POST");
        http_conn.setDoInput(true); 
        http_conn.setDoOutput(true); 
        http_conn.setRequestProperty("Content-type", "application/json; charset=utf-8"); 

        String login = URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");
        login += "&" + URLEncoder.encode("XXXXX", "UTF-8") + "=" + URLEncoder.encode("XX", "UTF-8");



        OutputStreamWriter wr = new OutputStreamWriter(http_conn.getOutputStream());
        //TERMINATES HERE
        wr.write(login);
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        String line = rd.toString();

        wr.close();
        rd.close();

        http_conn.disconnect();
        }
        catch (IOException e){
        }
}

这是我第一次接触 java,并且只写了几天,所以如果我错过了一些明显的东西,请耐心等待。

谢谢

最佳答案

如果您想使用 HTTP POST 某些内容,为什么不使用 HTTP POST? ;-)

这是一个示例 fragment :

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

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

来源:http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

关于Java 应用程序在 getOutputStream() 处终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11777230/

相关文章:

java - 在客户端和服务器进程之间使用ObjectInputStream和ObjectOutputStream

java - 删除数据库条目后刷新 ListView

java - 无法在托管 Bean 中注入(inject)数据源

java - 如何在使用 hibernate 作为 ORM 时执行基于语言环境的排序

Android 操作栏 SearchView NullPointerException adjustmentDropDownSizeAndPosition

android - 获取安卓 :windowSoftInputMode attribute programmatically on Android

java - AES PBE 在 Java 中加密/在 Ruby 中解密

android - 使用 Facebook 的移动托管 API 安装 android 应用程序,但无法获取查询数据?

c# - Azure Functions 使用两个输出 blob 调整 blob 大小

Java - 如何循环读取InputStream,直到用户输入继续?