Search Results

Search found 127 results on 6 pages for 'httpurlconnection'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Java HttpURLConnection class Program

    - by pandu
    I am learning java. Here is the sample code of HttpURLConnection class usage in some text book import java.net.*; import java.io.*; import java.util.*; class HttpURLDemo { public static void main(String args[]) throws Exception { URL hp = new URL("http://www.google.com"); HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection(); // Display request method. System.out.println("Request method is " + hpCon.getRequestMethod()); // Display response code. System.out.println("Response code is " + hpCon.getResponseCode()); // Display response message. System.out.println("Response Message is " + hpCon.getResponseMessage()); // Get a list of the header fields and a set // of the header keys. Map<String, List<String>> hdrMap = hpCon.getHeaderFields(); Set<String> hdrField = hdrMap.keySet(); System.out.println("\nHere is the header:"); // Display all header keys and values. for(String k : hdrField) { System.out.println("Key: " + k + " Value: " + hdrMap.get(k)); } } } Question is Why hpCon Object is declared in the following way? HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection(); instead of declaring like this HttpURLConnection hpCon = new HttpURLConnection(); Author provided the following explanation. I cant understand Java provides a subclass of URLConnection that provides support for HTTP connections. This class is called HttpURLConnection. You obtain an HttpURLConnection in the same way just shown, by calling openConnection( ) on a URL object, but you must cast the result to HttpURLConnection. (Of course, you must make sure that you are actually opening an HTTP connection.) Once you have obtained a reference to an HttpURLConnection object, you can use any of the methods inherited from URLConnection

    Read the article

  • HttpURLConnection getting locked

    - by Nayn
    Hi, I have a thread running under tomcat which creates a HttpUrlConnection and reads it through BufferedInputStream. After fetching data for some urls, it stalls. I got the jstack of the process which says HttpUrlConnection is locked and BufferedInputStream is also locked. "http-8080-1" daemon prio=10 tid=0x08683400 nid=0x79c9 runnable [0x8f618000] java.lang.Thread.State: RUNNABLE at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:129) at java.io.BufferedInputStream.fill(BufferedInputStream.java:218) at java.io.BufferedInputStream.read1(BufferedInputStream.java:258) at java.io.BufferedInputStream.read(BufferedInputStream.java:317) - locked <0x956ef8c0> (a java.io.BufferedInputStream) at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687) at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:632) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1072) - locked <0x956ef910> (a sun.net.www.protocol.http.HttpURLConnection) Could somebody help here. Thanks

    Read the article

  • HttpURLConnection inside a loop

    - by Carlos Garces
    Hi! I'm trying to connect to one URL that I know that exist but I don't know when. I don't have access to this server so I can't change anything to receive a event. The actual code is this. URL url = new URL(urlName); for(int j = 0 ; j< POOLING && disconnected; j++){ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int status = connection.getResponseCode(); if(status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_NOT_MODIFIED){ //Some work }else{ //wait 3s Thread.sleep(3000); } } Java not is my best skill and I'm not sure if this code is good from the point of view of performance. I'm opening a new connection every 3 seconds? or the connection is reused? If I call to disconnect() I ensure that no new connections are open in the loop, but... it will impact in performance?. Suggestions? What is the fast/best ways to know it a URL exist?

    Read the article

  • Android: HttpURLConnection not working properly

    - by giorgiline
    I'm trying to get the cookies from a website after sending user credentials through a POST Request an it seems that it doesn't work in android this way. ¿Am I doing something bad?. Please help. I've searched here in different posts but there's no useful answer. It's curious that this run in a desktop Java implementation it works perfect but it crashes in Android platform. And it is exactly the same code, specifically when calling HttpURLConnection.getHeaderFields(), it also happens with other member methods. It's a simple code and I don't know why the hell isn't working. DESKTOP CODE: This goes just in the main() HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ System.out.println("Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ System.out.println(cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } So the output is: login_key=20ad8177db4eca3f057c14a64bafc2c9 FASID=cabf20cc471fcacacdc7dc7e83768880 track=30c8183e4ebbe8b3a57b583166326c77 client-data=%7B%22ism%22%3Afalse%2C%22showm%22%3Afalse%2C%22ts%22%3A1349189669%7D ANDROID CODE: This goes inside doInBackground AsyncTask body HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ Log.v(TAG, "Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ Log.v(TAG, cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } And here there is no output, it seems that connection.getHeaderFields() doesn't return result. It takes al least 30 seconds to show the Log: 10-02 16:56:25.918: V/class com.giorgi.myproject.activities.HomeActivity(2596): Header null

    Read the article

  • HttpURLConnection: Is it necessary to call connect()?

    - by stormin986
    Many examples I've seen don't explicitly call connect(). Instead they just use getInputStream() or getResponseCode(). I'm assuming all of these HttpURLConnection methods that require a connection just call connect() themselves? Are there any cases where connect() must be explicitly called for an HttpURLConnection?

    Read the article

  • HttpURLConnection does not read the whole respnse

    - by Peter Szanto
    I use HttpURLConnection to do HTTP POST but I dont always get back the full response. I wanted to debug the problem, but when I step through each line it worked. I thought it must be a timing issue so I added Thread.sleep and it really made my code work, but this is only a temporary workaround. I wonder why is this happening and how to solve. Here is my code: URL u = new URL(url); URLConnection c = u.openConnection(); InputStream in = null; String mediaType = null; if (c instanceof HttpURLConnection) { //c.setConnectTimeout(1000000); //c.setReadTimeout(1000000); HttpURLConnection h = (HttpURLConnection)c; h.setRequestMethod("POST"); //h.setChunkedStreamingMode(-1); setAccept(h, expectedMimeType); h.setRequestProperty("Content-Type", inputMimeType); for(String key: httpHeaders.keySet()) { h.setRequestProperty(key, httpHeaders.get(key)); if (logger.isDebugEnabled()) { logger.debug("Request property key : " + key + " / value : " + httpHeaders.get(key)); } } h.setDoOutput(true); h.connect(); OutputStream out = h.getOutputStream(); out.write(input.getBytes()); out.close(); mediaType = h.getContentType(); logger.debug(" ------------------ sleep ------------------ START"); try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } logger.debug(" ------------------ sleep ------------------ END"); if (h.getResponseCode() < 400) { in = h.getInputStream(); } else { in = h.getErrorStream(); } It genearates the following HTTP headers POST /emailauthentication/ HTTP/1.1 Accept: application/xml Content-Type: application/xml Authorization: OAuth oauth_consumer_key="b465472b-d872-42b9-030e-4e74b9b60e39",oauth_nonce="YnDb5eepuLm%2Fbs",oauth_signature="dbN%2FWeWs2G00mk%2BX6uIi3thJxlM%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1276524919", oauth_token="", oauth_version="1.0" User-Agent: Java/1.6.0_20 Host: test:6580 Connection: keep-alive Content-Length: 1107 In other posts it was suggested to turn off keep-alive by using the http.keepAlive=false system property, I tried that and the headers changed to POST /emailauthentication/ HTTP/1.1 Accept: application/xml Content-Type: application/xml Authorization: OAuth oauth_consumer_key="b465472b-d872-42b9-030e-4e74b9b60e39", oauth_nonce="Eaiezrj6X4Ttt0", oauth_signature="ND9fAdZMqbYPR2j%2FXUCZmI90rSI%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1276526608", oauth_token="", oauth_version="1.0" User-Agent: Java/1.6.0_20 Host: test:6580 Connection: close Content-Length: 1107 the Connection header is "close" but I still cannot read the whole response. Any idea what do I do wrong?

    Read the article

  • HttpURLConnection: What is the minimum best-practice implementation?

    - by stormin986
    I've come across a lot of HttpURLConnection examples that are nothing more than openConnection(), getInputStream(), and then they just read the buffer and are done. It's simple but seems like it's not the best implementation ... it handles no problems. I don't yet know much about http, so I keep thinking I have everything covered until a new problem arises. I'm currently experiencing a similar problem to this one. Most times I try to read the same resource a second time (from a different HttpURLConnection object, after I .disconnect()'ed the previous one), the response code returns as -1 (but no exception is thrown!!). Before I knew to check the response code, I was baffled since I was throwing no exceptions. So, is there a minimum 'best practice' HttpURLConnection implementation? What are notable exceptions to handle? Request code checking? Any other error checks? What connection parameters do and don't need to be set (like doInput / doOutput, are these even necessary? Some examples have em, some don't). Etc. I realize this is kind of a broad question but I think it has potential to be a very useful resource if many of the common use cases and FAQs are addressed in one central place. This seems like the kind of thing a community wiki would be good for...

    Read the article

  • Java HttpURLConnection bekommt keine cookies

    - by TeNNoX
    ich versuche über eine HttpURLConnection einen Login auf einer Webseite durchzuführen, und davon dann die cookies zu erhalten... Bei meinen Testseiten auf einem eigenen Server geht es problemlos, ich sende "a=3&b=5" und als cookie erhalte ich "8", also die Summe. Wenn ich dies allerdings auf der gewollten Seite anwende, kommt einfach nur die Seite, als ob ich gar nichts per POST gesendet hätte... :( Generelle Verbesserungsvorschläge sind auch erwünscht! :) Mein Code: HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("useragent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0"); conn.setRequestProperty("Connection", "keep-alive"); DataOutputStream out = new DataOutputStream(conn.getOutputStream()); out.writeBytes("USER=tennox&PASS=*****"); out.close(); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String response = new String(); while ((line = in.readLine()) != null) { response = response + line + "\n"; } in.close(); System.out.println("headers:"); int i = 0; String header; while ((header = conn.getHeaderField(i)) != null) { String key = conn.getHeaderFieldKey(i); System.out.println(((key == null) ? "" : key + ": ") + header); i++; } String cookies = conn.getHeaderField("Set-Cookie"); System.out.println("\nCookies: \"" + cookies + "\"");

    Read the article

  • How to add parameters to HttpURLConnection using POST

    - by Michal Švácha
    I am trying to do POST with HttpURLConnection(I need to use it this way, can't use HttpPost) and I'd like to add parameters to that connection such as post.setEntity(new UrlEncodedFormEntity(nvp)); where nvp = new ArrayList<NameValuePair>(); having some data stored in. I can't find a way how to add this ArrayList to my HttpURLConnection which is here: HttpsURLConnection https = (HttpsURLConnection) url.openConnection(); https.setHostnameVerifier(DO_NOT_VERIFY); http = https; http.setRequestMethod("POST"); http.setDoInput(true); http.setDoOutput(true); the reason for that awkward https and http combination is the need for not verifying the certificate. That is not a problem, though, it posts. But I need it to post with arguments. Any ideas? Thanks a lot!

    Read the article

  • HttpURLConnection! Connection.getInputStream is java.io.FileNotFoundException

    - by user3643283
    I created a method "UPLPAD2" to upload file to server. Splitting my file to packets(10MB). It's OK (100%). But when i call getInputStream, i get FileNotFoundException. I think, in loop, i make new HttpURLConnection to set "setRequestProperty". This is a problem. Here's my code: @SuppressLint("NewApi") public int upload2(URL url, String filePath, OnProgressUpdate progressCallBack, AtomicInteger cancelHandle) throws IOException { HttpURLConnection connection = null; InputStream fileStream = null; OutputStream out = null; InputStream in = null; HttpResponse response = new HttpResponse(); Log.e("Upload_Url_Util", url.getFile()); Log.e("Upload_FilePath_Util", filePath); long total = 0; try { // Write the request. // Read from filePath and upload to server (url) byte[] buf = new byte[1024]; fileStream = new FileInputStream(filePath); long lenghtOfFile = (new java.io.File(filePath)).length(); Log.e("LENGHT_Of_File", lenghtOfFile + ""); int totalPacket = 5 * 1024 * 1024; // 10 MB int totalChunk = (int) ((lenghtOfFile + (totalPacket - 1)) / totalPacket); String headerValue = ""; String contentLenght = ""; for (int i = 0; i < totalChunk; i++) { long from = i * totalPacket; long to = 0; if ((from + totalPacket) > lenghtOfFile) { to = lenghtOfFile; } else { to = (totalPacket * (i + 1)); } to = to - 1; headerValue = "bytes " + from + "-" + to + "/" + lenghtOfFile; contentLenght = "Content-Length:" + (to - from + 1); Log.e("Conten_LENGHT", contentLenght); connection = client.open(url); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Range", headerValue); connection.setRequestProperty("Content-Length", Long.toString(to - from + 1)); out = connection.getOutputStream(); Log.e("Lenght_Of_File", lenghtOfFile + ""); Log.e("Total_Packet", totalPacket + ""); Log.e("Total_Chunk", totalChunk + ""); Log.e("Header_Valure", headerValue); int read = 1; while (read > 0 && cancelHandle.intValue() == 0 && total < totalPacket * (i + 1)) { read = fileStream.read(buf); if (read > 0) { out.write(buf, 0, read); total += read; progressCallBack .onProgressUpdate((int) ((total * 100) / lenghtOfFile)); } } Log.e("TOTAL_", total + "------" + totalPacket * (i + 1)); Log.e("I_", i + ""); Log.e("LENGHT_Of_File", lenghtOfFile + ""); if (i < totalChunk - 1) { connection.disconnect(); } out.close(); } // Read the response. response.setHttpCode(connection.getResponseCode()); in = connection.getInputStream(); // I GET ERROR HERE. if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { throw new IOException("Unexpected HTTP response: " + connection.getResponseCode() + " " + connection.getResponseMessage()); } byte[] body = readFully(in); response.setBody(body); response.setHeaderFields(connection.getHeaderFields()); if (cancelHandle.intValue() != 0) { return 1; } JSONObject jo = new JSONObject(response.getBodyAsString()); Log.e("Upload_Body_res_", response.getBodyAsString()); if (jo.has("error")) { if (jo.has("code")) { int errCode = jo.getInt("code"); Log.e("Upload_Had_errcode", errCode + ""); return errCode; } else { return 504; } } Log.e("RESPONE_BODY_UPLOAD", response.getBodyAsString() + ""); return 0; } catch (Exception e) { e.printStackTrace(); Log.e("Http_UpLoad_Response_Exception", e.toString()); response.setHttpCode(connection.getResponseCode()); Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode() + ""); if (connection.getResponseCode() == 200) { return 1; } else if (connection.getResponseCode() == 0) { return 1; } else { return response.getHttpCode(); } // Log.e("ErrorCode_Upload_Util_Return", response.getHttpCode()+""); } finally { if (fileStream != null) fileStream.close(); if (out != null) out.close(); if (in != null) in.close(); } } And Logcat 06-12 09:39:29.558: W/System.err(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x 06-12 09:39:29.558: W/System.err(30740): at com.squareup.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:187) 06-12 09:39:29.563: W/System.err(30740): at com.fsharemobile.client.HttpUtil.upload2(HttpUtil.java:383) 06-12 09:39:29.563: W/System.err(30740): at com.fsharemobile.fragments.ExplorerFragment$7$1.run(ExplorerFragment.java:992) 06-12 09:39:29.568: W/System.err(30740): at java.lang.Thread.run(Thread.java:856) 06-12 09:39:29.568: E/Http_UpLoad_Response_Exception(30740): java.io.FileNotFoundException: http://download-f77c.fshare.vn/upload/NRHAwh+bUCxjUtcD4cn9xqkADpdL32AT9pZm7zaboHLwJHLxOPxUX9CQxOeBRgelkjeNM5XcK11M1V-x

    Read the article

  • Reading HttpURLConnection InputStream - manual buffer or BufferedInputStream?

    - by stormin986
    When reading the InputStream of an HttpURLConnection, is there any reason to use one of the following over the other? I've seen both used in examples. Manual Buffer: while ((length = inputStream.read(buffer)) > 0) { os.write(buf, 0, ret); } BufferedInputStream is = http.getInputStream(); bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append(current); } EDIT I'm still new to HTTP in general but one consideration that comes to mind is that if I am using a persistent HTTP connection, I can't just read until the input stream is empty right? In that case, wouldn't I need to read the message length and just read the input stream for that length? And similarly, if NOT using a persistent connection, is the code I included 100% good to go in terms of reading the stream properly?

    Read the article

  • Reading HttpURLConnection InputStream - manual buffer or BufferedInputStream?

    - by stormin986
    When reading the InputStream of an HttpURLConnection, is there any reason to use one of the following over the other? I've seen both used in examples. Manual Buffer: while ((length = inputStream.read(buffer)) > 0) { os.write(buf, 0, ret); } BufferedInputStream is = http.getInputStream(); bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append(current); } EDIT I'm still new to HTTP in general but one consideration that comes to mind is that if I am using a persistent HTTP connection, I can't just read until the input stream is empty right? In that case, wouldn't I need to read the message length and just read the input stream for that length? And similarly, if NOT using a persistent connection, is the code I included 100% good to go in terms of reading the stream properly?

    Read the article

  • Server returns 500 error only when called by Java client using urlConnection/httpUrlConnection

    - by user455889
    Hi - I'm having a very strange problem. I'm trying to call a servlet (JSP) with an HTTP GET and a few parameters (http://mydomain.com/method?param1=test&param2=123). If I call it from the browser or via WGET in a bash session, it works fine. However, when I make the exact same call in a Java client using urlConnection or httpURLConnection, the server returns a 500 error. I've tried everything I have found online including: urlConn.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); Nothing I've tried, however, has worked. Unfortunately, I don't have access to the server I'm calling so I can't see the logs. Here's the latest code: private String testURLConnection() { String ret = ""; String url = "http://localhost:8080/TestService/test"; String query = "param1=value1&param2=value2"; try { URLConnection connection = new URL(url + "?" + query).openConnection(); connection.setRequestProperty("Accept-Charset", "UTF-8"); connection.setRequestProperty("Accept-Language", "en-us,en;q=0.5"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuilder content = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); } bufferedReader.close(); metaRet = content.toString(); log.debug(methodName + " return = " + metaRet); } catch (Exception ex) { log.error("Exception: " + ex); log.error("stack trace: " + getStackTrace(ex)); } return metaRet; } Any help would be greatly appreciated!

    Read the article

  • HttpURLConnection timeout question

    - by Malachi
    I want to return false if the URL takes more then 5 seconds to connect - how is this possible using java? Here is the code I am using to check if the URL is valid HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK);

    Read the article

  • HttpURLConnection: What's the deal with having to read the whole response?

    - by stormin986
    My current problem is very similar to this one. I have a downloadFile(URL) function that creates a new HttpURLConnection, opens it, reads it, returns the results. When I call this function on the same URL multiple times, the second time around it almost always returns a response code of -1 (But throws no exception!!!). The top answer in that question is very helpful, but there are a few things I'm trying to understand. So, if setting http.keepAlive to false solves the problem, it indicates what exactly? That the server is responding in a way that violates the http protocol? Or more likely, my code is violating the protocol in some way? What will the trace tell me? What should I look for? And what's the deal with this: You need to read everything from error stream. Otherwise, it's going to confuse next connection and that's the cause of -1. Does this mean if the response is some type of error (which would be what response code(s)?), the stream HAS to be fully read? Also, every time I am attempting an http request I am basically creating a new connection, and then disconnect()ing it at the end. However, in my case I'm not getting a 401 or whatever. It's always a 200. But my second connection almost always fails. Does this mean there's some other data I should be reading that I'm not (in a similar manner that the error stream must be fully read)? Please help shed some light on this? I feel like there's some fundamental http protocol understanding I'm missing.

    Read the article

  • android httpurlconnection [closed]

    - by user620451
    hi im new android developer i am trying to login to my asterisk server passing my username and password it works good but when i am trying to request anther url to the server after login i get access denied and i now the problem because the login connection has disconnected so i want a way to request to urls the first one is login to the server and the second is to do something else after login please help and thx anyway this is a part of my code i want to request this 2 url url1="http://192.168.1.7:8088/rawman?action=login&username=admin&secret=admin" url2="http://192.168.1.5:8088/rawman?action=updateconfig&reload=yes&srcfilename=users.conf&dstfilename=users.conf&Action-000000=newcat&Cat-000000=6001&Var-000000=&Value-000000=" public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv1 = (TextView) this.findViewById(R.id.display); ed1 = (EditText) this.findViewById(R.id.editText); bt1 = (Button) this.findViewById(R.id.submit); bt1.setOnClickListener(new OnClickListener() { public void onClick(View view) { { try{ ServerRequest(url1); ServerRequest(url2); } catch(Exception e) { Log.v("Exception", "Exception:"+e.getMessage()); } } } }); } public String ServerRequest(String serverString) throws MalformedURLException, IOException { String newFeed=serverString; StringBuilder response = new StringBuilder(); Log.v("server","server url:"+newFeed); URL url = new URL(newFeed); HttpURLConnection httpconn = (HttpURLConnection) url.openConnection(); if(httpconn.getResponseCode()==HttpURLConnection.HTTP_OK) { BufferedReader input = new BufferedReader( new InputStreamReader(httpconn.getInputStream()), 8192); String strLine = null; while ((strLine = input.readLine()) != null) { response.append(strLine); } input.close(); } tv1.settext(response); return response.toString(); }

    Read the article

  • httpURLConnection vs apache commons http

    - by Pablo Fernandez
    Hi everyone! I just wanted to know if any of you had any problems using java default HttpURLConnection class. Some kind of bug that made you switch to apache commons. Or is it just the (ugly) interface that class exposes that justifies the birth of 3rd party http lib? Disclosure: I heard some arguments against java.net having some serious problems, but I'm finding hard to believe that a class that is part of the java core distribution still has issues after several releases of the JDK

    Read the article

  • Sending JSON to a server

    - by SK9
    I'm running the following Java, an HttpURLConnection PUT request with JSON data that will be sent from an Android device. I'll handle any raised exceptions after this is working. Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(nameString, pwdString.toCharArray()); } }); url = new URL(myURLString); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setChunkedStreamingMode(0); urlConnection.setRequestMethod("PUT"); urlConnection.setRequestProperty("Content-Type", "application/json"); OutputStream output = null; try { output = urlConnection.getOutputStream(); output.write(jsonArray.toString().getBytes()); } finally { if (output != null) { output.close(); } } int status = ((HttpURLConnection) urlConnection).getResponseCode(); System.out.println("" + status); urlConnection.disconnect(); I'm receiving an HTTP 500 error (internal error code), that an unexpected property is blocking the request. The JSONArray comprises JSONObjects whose keys I know are correct. The server is pretty standard, and expects HTTP PUTs with JSON bodies. Am I missing something glaring? Thanking you kindly in advance.

    Read the article

  • Does writing data to server using Java URL class require response from server?

    - by gigadot
    I am trying to upload files using Java URL class and I have found a previous question on stack-overflow which explains very well about the details, so I try to follow it. And below is my code adopted from the sniplet given in the answer. My problem is that if I don't make a call to one of connection.getResponseCode() or connection.getInputStream() or connection.getResponseMessage() or anything which is related to reponse from the server, the request will never be sent to server. Why do I need to do this? Or is there any way to write the data without getting the response? P.S. I have developed a server-side uploading servlet which accepts multipart/form-data and save it to files using FileUpload. It is stable and definitely working without any problem so this is not where my problem is generated. import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import org.apache.commons.io.IOUtils; public class URLUploader { public static void closeQuietly(Closeable... objs) { for (Closeable closeable : objs) { IOUtils.closeQuietly(closeable); } } public static void main(String[] args) throws IOException { File textFile = new File("D:\\file.zip"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:8080/upslet/upload").openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream output = output = connection.getOutputStream(); PrintWriter writer = writer = new PrintWriter(output, true); // Send text file. writer.println("--" + boundary); writer.println("Content-Disposition: form-data; name=\"file1\"; filename=\"" + textFile.getName() + "\""); writer.println("Content-Type: application/octet-stream"); FileInputStream fin = new FileInputStream(textFile); writer.println(); IOUtils.copy(fin, output); writer.println(); // End of multipart/form-data. writer.println("--" + boundary + "--"); output.flush(); closeQuietly(fin, writer, output); // Above request will never be sent if .getInputStream() or .getResponseCode() or .getResponseMessage() does not get called. connection.getResponseCode(); } }

    Read the article

  • Android problem: BufferedReader wont read whole stream into a string

    - by Levara
    Hi all! I'm making an android program that retrieves content of a webpage using HttpURLConnection. I'm new to both Java and Android. Problem is: Reader reads whole page source, but in the last while iteration it doesn't append to stringBuffer that last part. Using debbuger I have determined that, in the last loop iteration, string buff is created, but stringBuffer just doesnt append it. I need to parse retrieved content. Is there any better way to handle the content for parsing than using strings. I've read on numerous other sites that string size in Java is limited only by available heap size. Anyone know what could be the problem. Btw feel free to suggest any improvements to the code. Thanks! URL u; try { u = new URL("http://feeds.timesonline.co.uk/c/32313/f/440134/index.rss"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestProperty("User-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)"); c.setRequestMethod("GET"); c.setDoOutput(true); c.setReadTimeout(3000); c.connect(); StringBuffer stringBuffer = new StringBuffer(""); InputStream in = c.getInputStream(); InputStreamReader inp = new InputStreamReader(in); BufferedReader reader = new BufferedReader(inp); char[] buffer = new char[3072]; int len1 = 0; while ( (len1 = reader.read(buffer)) != -1 ) { String buff = new String(buffer,0,len1); stringBuffer.append(buff); } String stranica = new String(stringBuffer); c.disconnect(); reader.close(); inp.close(); in.close();

    Read the article

  • StringBuffer wont read whole stream into a string (JAVA/Android)

    - by Levara
    Hi all! I'm making an android program that retrieves content of a webpage using HttpURLConnection. I'm new to both Java and Android. Problem is: Reader reads whole page source, but in the last while iteration it doesn't append to stringBuffer that last part. Using debbuger I have determined that, in the last loop iteration, string buff is created, but stringBuffer just doesnt append it. I need to parse retrieved content. Is there any better way to handle the content for parsing than using strings. I've read on numerous other sites that string size in Java is limited only by available heap size. I've tried with StringBuilder too. Anyone know what could be the problem. Btw feel free to suggest any improvements to the code. Thanks! URL u; try { u = new URL("http://feeds.timesonline.co.uk/c/32313/f/440134/index.rss"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestProperty("User-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; InfoPath.1; .NET CLR 2.0.50727)"); c.setRequestMethod("GET"); c.setDoOutput(true); c.setReadTimeout(3000); c.connect(); StringBuffer stringBuffer = new StringBuffer(""); InputStream in = c.getInputStream(); InputStreamReader inp = new InputStreamReader(in); BufferedReader reader = new BufferedReader(inp); char[] buffer = new char[3072]; int len1 = 0; while ( (len1 = reader.read(buffer)) != -1 ) { String buff = new String(buffer,0,len1); stringBuffer.append(buff); } String stranica = new String(stringBuffer); c.disconnect(); reader.close(); inp.close(); in.close();

    Read the article

  • Parse Exception: At line 1, column 0: no element found

    - by Jeffrey
    Hi everyone, I have a weird issue. I receive the following error that causes a force-close: org.apache.harmony.xml.ExpatParser$ParseException: At line 1, column 0: no element found at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:508) at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:467) at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:329) at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:286) After clicking the Force Close button, the Activity is recreated and the parsing completes without a hitch. I'm using the following code snippet inside doInBackground of an AsyncTask: URL serverAddress = new URL(url[0]); HTTPURLConnection connection = (HttpURLConnection) serverAddress.openConnection(); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setReadTimeout(10000); connection.connect(); InputStream stream = connection.getInputStream(); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.parse(new InputSource(stream)); // The line that throws the exception Why would the Activity force-close and then run without any problems immediately after? Would a BufferedInputStream be any different? I'm baffled. :( Thanks for your time everyone.

    Read the article

  • Retrieving Json via HTML request from Jboss server

    - by Seth Solomon
    I am running into a java.net.SocketException: Unexpected end of file from server when I am trying to query some JSON from my JBoss server. I am hoping someone can spot where I am going wrong. Or does anyone have any suggestions of a better way to pull this JSON from my Jboss server? try{ URL u = new URL("http://localhost:9990/management/subsystem/datasources/data-source/MySQLDS/statistics?read-resource&include-runtime=true&recursive=true"); HttpURLConnection c = (HttpURLConnection) u.openConnection(); String encoded = Base64.encode(("username"+":"+"password").getBytes()); c.setRequestMethod("POST"); c.setRequestProperty("Authorization", "Basic "+encoded); c.setRequestProperty("Content-Type","application/json"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(5000); c.setReadTimeout(5000); c.connect(); int status = c.getResponseCode(); // throws the exception here switch (status) { case 200: case 201: BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line+"\n"); } br.close(); System.out.println(sb.toString()); break; default: System.out.println(status); break; } } catch (Exception e) { e.printStackTrace(); }

    Read the article

  • WebRequest using c# (VS2008) is perfectly working but not on JAVA (Ecplise)

    - by Daniel
    Hi, I'm trying to read data from a webpage, and I have to do it using JAVA. When I try to do it in Eclipse using JAVA i'm getting time out error: java.net.ConnectException: Connection timed out: connect (Using HttpURLConnection) In order to understand where is the problem I tried doing the same task using c# and VS2008, and it worked perfectly fine, no time out at all. What can be the reason for this? Thanks! Daniel

    Read the article

1 2 3 4 5 6  | Next Page >