JSON from PHP file returns garbage - java
I'm trying to get a JSON file from my site example.net/index.php, however I always get some kind of HTML in an Android app rather than JSON object.
Returned string:
<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("674bdf26f9a5fe3df1461aafc3120641");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://example.net/index.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
Called url:
<?php
$results = array(
"result" => "success",
"username" => "some username",
"projects" => "some other value"
);
header('Content-type: application/json');
echo json_encode($results);
?>
Code:
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
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();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
How do I get the JSON file instead of this HTML code?
You should pass the content type,
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setRequestProperty("Content-type", "application/json; charset=utf-8");
c.setUseCaches(false);
Well look at what the html source is trying to tell you:
This site requires Javascript to work,
You should first use a javascript interpreter on that page to obtain json.
So wrong url. It does not give you json.
If you request that page with a browser the browser will invoke the javascript interpreter without you knowing it.
Related
PHP returned JSON looks like HTML code
I have an Android app, and I send a Http request via getJson() method to get a generated JSON file from the web server. However, the result I always get in my Android app looks like this (looks like HTML, not like a JSON object): I/System.out: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("674bdf26f9a5fe3df1461aafc3120641");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://example.net/index.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html> index.php <?php $results = array( "result" => "success", "username" => "some username", "projects" => "some other value" ); header('Content-type: application/json'); echo json_encode($results); ?> Connection method: public String getJSON(String url, int timeout) { HttpURLConnection c = null; try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); 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(); return sb.toString(); } } catch (MalformedURLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } finally { if (c != null) { try { c.disconnect(); } catch (Exception ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } } } return null; } Call: String data = getJSON("http://example.net", 10000); // or String data = getJSON("http://example.net/index.php", 10000); System.out.println(data); The "example.net" URL is a valid URL, where it shows correctly the JSON file when opened in the browser. Question: How do I obtain JSON file in an Android app, when Android's HttpURLConnection doesn't support JavaScript?
Android HttpURLConnection setRequestMethod PUT
I'm trying to connect an Android app to a restful server with HttpURLConnection. The GET requests are successful but the PUT requests aren't. Every PUT request arrives at the server as a GET request. #Override protected Boolean doInBackground(Method... params) { Boolean result = false; try { URL url = new URL("http://server.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); switch (params[0]) { case PUT: connection.setDoOutput(true); connection.setRequestMethod("PUT"); Log.d(TAG, "Method: " + connection.getRequestMethod()); // Correctly "Method: PUT" OutputStreamWriter out = new OutputStreamWriter( connection.getOutputStream()); out.write("Message"); out.close(); break; case GET: connection.setRequestMethod("GET"); connection.connect(); break; default: connection.setRequestMethod("GET"); connection.connect(); break; } if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream in = connection.getInputStream(); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("state")) { result = true; if (reader.nextInt() == 1) { state = true; Log.d(TAG, "state: 1"); } else { state = false; Log.d(TAG, "state: -1"); } } else if (name.equals("method")) { method = reader.nextString(); // Server respone is "Method: GET" } } reader.endObject(); in.close(); } else { Log.d(TAG, "Connection failed"); } connection.disconnect(); } catch (Exception e) { Log.e("Exception", e.toString()); e.printStackTrace(); } return result; } The request method is correctly set to PUT before connection.connect();. What am I missing? I don't want to send data. The PUT request changes a counter, so no data is necessary. Same function is implemented in Javascript with JQuery for a webfrontend and works $.ajax({ url: '/api', method: 'PUT' }); EDIT: Maybe it's a problem with the server. Currently I'm using an php file <?php echo(var_dump($_SERVER)); // ["REQUEST_METHOD"]=> string(3) "GET" function get ($db) { $state = $db->querySingle('SELECT state FROM states WHERE name="main"'); echo('{"state": ' . $state . ', "method": "get"}'); } function put ($db) { $state = $db->querySingle('SELECT state FROM states WHERE name="main"'); $db->exec('UPDATE states SET state=' . ($state+1)%2 . ' WHERE name="main"'); $state = $db->querySingle('SELECT state FROM states WHERE name="main"'); echo('{"state": ' . $state . ', "method": "put"}'); } if ($db = new SQLite3('database.sqlite')) { switch($_SERVER['REQUEST_METHOD']){ case 'GET': get($db); break; case 'PUT': put($db); break; } $db->close(); } else { } ?> I tried my app with http://httpbin.org/put and it worked.
I found the problem. I have to append a trailing slash to the url otherwise the request is redirected and transformed to a GET request. I don't exactly understand the problem but I found a solution for me. I have to change URL url = new URL("http://server.com/api"); to URL url = new URL("http://server.com/api/"); And now it works. Maybe someone can explain it to me. When I try to open http://server.com/api with curl I get a 303 redirect to http://server.com/api.
HttpUrlConnection BadRequest - Statuscode 400
I have implemented a class using HttpUrlConnection to get some data from the google geocoding api. When I'm using this code on android, it works properly. But as soon as I am using this code in another "normal" java program, I am getting the status-code 400 (BadRequest) sometimes. Here is my code: HttpURLConnection c = null; StringBuilder sb = new StringBuilder(); try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); switch (status) { case HttpURLConnection.HTTP_OK: case HttpURLConnection.HTTP_CREATED: BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream())); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); } } catch (SocketTimeoutException ex){ // Handle ... } catch (MalformedURLException ex) { // Handle ... } catch (IOException ex) { // Handle ... } finally { if (c != null) { try { c.disconnect(); } catch (Exception ex) { } } } I have a reliable internet connection and also the URL I am using to receive the data works, whenever I try it with my web browser. Thanks in advance!
Bad Request is often caused by inadequat URLs. As you mentioned not every URL gives this error, only a view of them. So it has to be something to do with that. Try the following code to ensure the correct encoding of the URL you are using: String url = ...; // your url url = URLEncoder.encode(url,"UTF-8"); // Use 'url' ...
HTTP Request to Wikipedia gives no result
I try to fetch HTML per Code. When fetching from "http://www.google.com" for example it works perfect. When trying to fetch from "http://en.wikipedia.org/w/api.php" I do not get any results. Does someone have any idea ? Code: String sURL="http://en.wikipedia.org/w/api.php?action=query&generator=categorymembers&gcmtitle=Category:Countries&prop=info&gcmlimit=500&format=json"; String sText=readfromURL(sURL); public static String readfromURL(String sURL){ URL url = null; try { url = new URL(sURL); } catch (MalformedURLException e1) { e1.printStackTrace(); } URLConnection urlconnect = null; try { urlconnect = url.openConnection(); urlconnect.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0"); } catch (IOException e) { e.printStackTrace(); } BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(urlconnect.getInputStream())); } catch (IOException e) { e.printStackTrace(); } String inputLine; String sEntireContent=""; try { while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); sEntireContent=sEntireContent+inputLine; } } catch (IOException e) { e.printStackTrace(); } try { in.close(); } catch (IOException e) { e.printStackTrace(); } return sEntireContent; }
It looks like the request limit. Try to check the response code. From the documentation (https://www.mediawiki.org/wiki/API:Etiquette): If you make your requests in series rather than in parallel (i.e. wait for the one request to finish before sending a new request, such that you're never making more than one request at the same time), then you should definitely be fine. Be sure that you do not do few request at a time Update I did verification on my local your code - you are correct it does not work. Fix - you need to use https, so it would work: https://en.wikipedia.org/w/api.php?action=query&generator=categorymembers&gcmtitle=Category:Countries&prop=info&gcmlimit=500&format=json result: {"batchcomplete":"","query":{"pages":{"5165":{"pageid":5165,"ns":0,"title":"Country","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T20:09:05Z","lastrevid":686706429,"length":12695},"5112305":{"pageid":5112305,"ns":14,"title":"Category:Countries by continent","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T17:31:54Z","lastrevid":681415612,"length":133},"14353213":{"pageid":14353213,"ns":14,"title":"Category:Countries by form of government","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-08-13T23:33:29Z","lastrevid":675984011,"length":261},"5112467":{"pageid":5112467,"ns":14,"title":"Category:Countries by international organization","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T05:11:12Z","lastrevid":686245148,"length":123},"4696391":{"pageid":4696391,"ns":14,"title":"Category:Countries by language","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T01:17:18Z","lastrevid":675966601,"length":333},"5112374":{"pageid":5112374,"ns":14,"title":"Category:Countries by status","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-08-13T21:05:47Z","lastrevid":675966630,"length":30},"708617":{"pageid":708617,"ns":14,"title":"Category:Lists of countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T05:08:45Z","lastrevid":681553760,"length":256},"46624537":{"pageid":46624537,"ns":14,"title":"Category:Caspian littoral states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-23T08:40:34Z","lastrevid":663549987,"length":50},"18066512":{"pageid":18066512,"ns":14,"title":"Category:City-states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-29T20:14:14Z","lastrevid":679367764,"length":145},"2019528":{"pageid":2019528,"ns":14,"title":"Category:Country classifications","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-25T09:09:13Z","lastrevid":675966465,"length":182},"935240":{"pageid":935240,"ns":14,"title":"Category:Country codes","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T06:05:53Z","lastrevid":546489724,"length":222},"36819536":{"pageid":36819536,"ns":14,"title":"Category:Countries in fiction","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-03T06:09:16Z","lastrevid":674147667,"length":169},"699787":{"pageid":699787,"ns":14,"title":"Category:Fictional countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T18:43:25Z","lastrevid":610289877,"length":356},"804303":{"pageid":804303,"ns":14,"title":"Category:Former countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-21T09:58:52Z","lastrevid":668632882,"length":403},"7213567":{"pageid":7213567,"ns":14,"title":"Category:Island countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-22T22:10:37Z","lastrevid":648502876,"length":157},"3046541":{"pageid":3046541,"ns":14,"title":"Category:Landlocked countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-04T00:45:24Z","lastrevid":648502892,"length":54},"743058":{"pageid":743058,"ns":14,"title":"Category:Middle Eastern countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-12T14:41:59Z","lastrevid":677900732,"length":495},"41711462":{"pageid":41711462,"ns":14,"title":"Category:Mongol states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-23T07:36:21Z","lastrevid":687093637,"length":121},"30645082":{"pageid":30645082,"ns":14,"title":"Category:Country names","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-03-07T06:33:19Z","lastrevid":561256656,"length":94},"21218559":{"pageid":21218559,"ns":14,"title":"Category:Outlines of countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-07T18:04:29Z","lastrevid":645312408,"length":248},"37943702":{"pageid":37943702,"ns":14,"title":"Category:Proposed countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T02:30:25Z","lastrevid":668630396,"length":130},"15086044":{"pageid":15086044,"ns":14,"title":"Category:Turkic states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T06:23:35Z","lastrevid":677424552,"length":114},"32809189":{"pageid":32809189,"ns":14,"title":"Category:Works about countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T08:45:32Z","lastrevid":620016516,"length":153},"27539189":{"pageid":27539189,"ns":14,"title":"Category:Wikipedia books on countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-04-11T05:12:25Z","lastrevid":546775798,"length":203},"35317198":{"pageid":35317198,"ns":14,"title":"Category:Wikipedia categories named after countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T18:35:14Z","lastrevid":641689352,"length":202}}}} {"batchcomplete":"","query":{"pages":{"5165":{"pageid":5165,"ns":0,"title":"Country","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T20:09:05Z","lastrevid":686706429,"length":12695},"5112305":{"pageid":5112305,"ns":14,"title":"Category:Countries by continent","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T17:31:54Z","lastrevid":681415612,"length":133},"14353213":{"pageid":14353213,"ns":14,"title":"Category:Countries by form of government","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-08-13T23:33:29Z","lastrevid":675984011,"length":261},"5112467":{"pageid":5112467,"ns":14,"title":"Category:Countries by international organization","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T05:11:12Z","lastrevid":686245148,"length":123},"4696391":{"pageid":4696391,"ns":14,"title":"Category:Countries by language","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T01:17:18Z","lastrevid":675966601,"length":333},"5112374":{"pageid":5112374,"ns":14,"title":"Category:Countries by status","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-08-13T21:05:47Z","lastrevid":675966630,"length":30},"708617":{"pageid":708617,"ns":14,"title":"Category:Lists of countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-18T05:08:45Z","lastrevid":681553760,"length":256},"46624537":{"pageid":46624537,"ns":14,"title":"Category:Caspian littoral states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-23T08:40:34Z","lastrevid":663549987,"length":50},"18066512":{"pageid":18066512,"ns":14,"title":"Category:City-states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-29T20:14:14Z","lastrevid":679367764,"length":145},"2019528":{"pageid":2019528,"ns":14,"title":"Category:Country classifications","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-25T09:09:13Z","lastrevid":675966465,"length":182},"935240":{"pageid":935240,"ns":14,"title":"Category:Country codes","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T06:05:53Z","lastrevid":546489724,"length":222},"36819536":{"pageid":36819536,"ns":14,"title":"Category:Countries in fiction","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-03T06:09:16Z","lastrevid":674147667,"length":169},"699787":{"pageid":699787,"ns":14,"title":"Category:Fictional countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T18:43:25Z","lastrevid":610289877,"length":356},"804303":{"pageid":804303,"ns":14,"title":"Category:Former countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-09-21T09:58:52Z","lastrevid":668632882,"length":403},"7213567":{"pageid":7213567,"ns":14,"title":"Category:Island countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-22T22:10:37Z","lastrevid":648502876,"length":157},"3046541":{"pageid":3046541,"ns":14,"title":"Category:Landlocked countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-04T00:45:24Z","lastrevid":648502892,"length":54},"743058":{"pageid":743058,"ns":14,"title":"Category:Middle Eastern countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-12T14:41:59Z","lastrevid":677900732,"length":495},"41711462":{"pageid":41711462,"ns":14,"title":"Category:Mongol states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-23T07:36:21Z","lastrevid":687093637,"length":121},"30645082":{"pageid":30645082,"ns":14,"title":"Category:Country names","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-03-07T06:33:19Z","lastrevid":561256656,"length":94},"21218559":{"pageid":21218559,"ns":14,"title":"Category:Outlines of countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-07T18:04:29Z","lastrevid":645312408,"length":248},"37943702":{"pageid":37943702,"ns":14,"title":"Category:Proposed countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T02:30:25Z","lastrevid":668630396,"length":130},"15086044":{"pageid":15086044,"ns":14,"title":"Category:Turkic states","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-20T06:23:35Z","lastrevid":677424552,"length":114},"32809189":{"pageid":32809189,"ns":14,"title":"Category:Works about countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T08:45:32Z","lastrevid":620016516,"length":153},"27539189":{"pageid":27539189,"ns":14,"title":"Category:Wikipedia books on countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-04-11T05:12:25Z","lastrevid":546775798,"length":203},"35317198":{"pageid":35317198,"ns":14,"title":"Category:Wikipedia categories named after countries","contentmodel":"wikitext","pagelanguage":"en","touched":"2015-10-17T18:35:14Z","lastrevid":641689352,"length":202}}}}
The reason you didn't receive the response back is due to a HTTP Redirect 3XX. Wikipedia redirects your HTTP Request. Please try the below source code to fetch Response from Redirected URL. Please refer How to send HTTP request GET/POST in Java public static String readfromURLwithRedirect(String url) { String response = ""; try { URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setReadTimeout(5000); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); System.out.println("Request URL ... " + url); boolean redirect = false; // normally, 3xx is redirect int status = conn.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { redirect = true; } } System.out.println("Response Code ... " + status); if (redirect) { // get redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); // get the cookie if need, for login String cookies = conn.getHeaderField("Set-Cookie"); // open the new connnection again conn = (HttpURLConnection) new URL(newUrl).openConnection(); conn.setRequestProperty("Cookie", cookies); conn.addRequestProperty("Accept-Language", "en-US,en;q=0.8"); conn.addRequestProperty("User-Agent", "Mozilla"); conn.addRequestProperty("Referer", "google.com"); System.out.println("Redirect to URL : " + newUrl); } BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer responseBuffer = new StringBuffer(); while ((inputLine = in.readLine()) != null) { responseBuffer.append(inputLine); } in.close(); System.out.println("URL Content... \n" + responseBuffer.toString()); response = responseBuffer.toString(); System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } return response; }
Sending SMS through low end API
I have a message constructor method of the form: public static String constructMsg(CustomerInfo customer) { ... snipped String msg = String.format("Snipped code encapsulated by customer object"); return msg; } The API link is: http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx &password=xxxx &type=0 &dlr=1&destination=10digitno & source=xxxxxx& message=xxxxx In my main method I have(s): List<CustomerInfo> customer = dao.getSmsDetails(userDate); theLogger.info("Total No : " + customer.size() ); if (!customer.isEmpty()) { for (CustomerInfo cust : customer) { String message = constructMsg(cust); // Add link and '?' and query string // use URLConnection's connect method } } So I am using connect method of URLConnection. The API does not have any documentation. Is there any way for checking response? My other question is, I have been advised to use ThreadPoolExecutor. How would I use use it here?
This method use HTTPURLConnection to perform a GET request returning the response as a String. There're many way to do it, this is not particularly brilliant but it's really readable. public String getResponse(String url, int timeout) { HttpURLConnection c; try { URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Content-length", "0"); c.setUseCaches(false); c.setAllowUserInteraction(false); c.setConnectTimeout(timeout); c.setReadTimeout(timeout); c.connect(); int status = c.getResponseCode(); 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(); return sb.toString(); default: return "HTTP CODE: "+status; } } catch (MalformedURLException ex) { Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(DebugServer.class.getName()).log(Level.SEVERE, null, ex); } finally{ if(c!=null) c.disconnect(); } return null; } Call this method like this: getResponse("http://xxx.xxx.xx.xx:8080/bulksms?username=xxxxxxx&password=xxxx&type=0 &dlr=1&destination=10digitno&source=xxxxxx&message=xxxxx",2000); I assume the whitespaces in your URL are not supposed to be there.