简体   繁体   English

Java应用程序终止于getOutputStream()

[英]Java application terminates at getOutputStream()

I'm creating an application for our Android devices. 我正在为我们的Android设备创建一个应用程序。 The aim of this section is to post a username and password (currently just assigned as a string) to a web service and to receive a login token. 本部分的目的是将用户名和密码(当前仅作为字符串分配)发布到Web服务并接收登录令牌。 When running the code, at the getOutputStream() line, my code terminates and will no progress any further. 运行代码时,在getOutputStream()行中,我的代码终止,并且不会继续进行下去。

I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. 我已经为Android仿真器分配了GSM访问权限,并且还在Eclipse中设置了代理和DNS服务器。 I'm not sure where to go with it now! 我不确定现在在哪里使用它!

This is within my onHandleIntent(): 这在我的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){
        }
}

This is my first go at java and have only been writing it for a few days so bear with me if I've missed something obvious. 这是我第一次尝试Java,并且只写了几天,所以如果我错过了明显的事情,请多多包涵。

Thanks 谢谢

If you want to POST something using HTTP, why not use HTTP POST? 如果要使用HTTP进行发布,为什么不使用HTTP POST? ;-) ;-)

Here is an example snippet: 这是一个示例片段:

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
    }
}

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

This may not be the appropriate answer, but will certainly be helpful to you. 这可能不是合适的答案,但肯定会对您有所帮助。 I have used this code for sending and receiving the request and reply resp, to a webservice. 我已经使用此代码向Web服务发送和接收请求和回复。

This code is working, but will need some Refactoring , as i have used some extra variable, which are not needed. 这段代码可以正常工作,但是需要一些Refactoring ,因为我已经使用了一些多余的变量,而这些变量是不需要的。

I have used the NameValuePair here for Post 我在这里使用了NameValuePair进行发布

public String postData(String url, String xmlQuery) {



        final String urlStr = url;
        final String xmlStr = xmlQuery;
        final StringBuilder sb  = new StringBuilder();


        Thread t1 = new Thread(new Runnable() {

            public void run() {

                HttpClient httpclient = new DefaultHttpClient();


                HttpPost httppost = new HttpPost(urlStr);


                try {

                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
                            1);
                    nameValuePairs.add(new BasicNameValuePair("xml", xmlStr));

                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    HttpResponse response = httpclient.execute(httppost);

                    Log.d("Vivek", response.toString());

                    HttpEntity entity = response.getEntity();
                    InputStream i = entity.getContent();

                    Log.d("Vivek", i.toString());
                    InputStreamReader isr = new InputStreamReader(i);

                    BufferedReader br = new BufferedReader(isr);

                    String s = null;


                    while ((s = br.readLine()) != null) {

                        Log.d("YumZing", s);
                        sb.append(s);
                    }


                    Log.d("Check Now",sb+"");




                } catch (ClientProtocolException e) {

                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } /*
                 * catch (ParserConfigurationException e) { // TODO
                 * Auto-generated catch block e.printStackTrace(); } catch
                 * (SAXException e) { // TODO Auto-generated catch block
                 * e.printStackTrace(); }
                 */
            }

        });

        t1.start();
        try {
            t1.join();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        System.out.println("Getting from Post Data Method "+sb.toString());

        return sb.toString();
    }
String line = rd.toString();

should be 应该

String line = rd.readLine();

that might do the trick. 这可能会解决问题。 rd.toString() gives you a String representation of your BufferedReader . rd.toString()为您提供BufferedReader的字符串表示形式。 It does not trigger the HTTP operation. 它不会触发HTTP操作。 I did not test your code, so there might be other errors as well, this was just the obvious one. 我没有测试您的代码,因此可能还会出现其他错误,这只是显而易见的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM