简体   繁体   中英

Java application terminates at getOutputStream()

I'm creating an application for our Android devices. 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. When running the code, at the getOutputStream() line, my code terminates and will no progress any further.

I have assigned the android emulator GSM access and also set the proxy and DNS server within Eclipse. I'm not sure where to go with it now!

This is within my 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.

Thanks

If you want to POST something using HTTP, why not use 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

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.

This code is working, but will need some Refactoring , as i have used some extra variable, which are not needed.

I have used the NameValuePair here for Post

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 . It does not trigger the HTTP operation. I did not test your code, so there might be other errors as well, this was just the obvious one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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