Android HttpURLConnection setRequestMethod PUT - java
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.
Related
Android - If statement gets ignored and bypassed
I am calling a PHP script from a function like this: public static String XSSignUp(String username, String password, String email, String signInWith) { // Paramenters Map<String, Object> params = new LinkedHashMap<>(); params.put(USERS_USERNAME, username); params.put(USERS_PASSWORD, password); params.put(USERS_EMAIL, email); params.put("signInWith", signInWith); params.put(USERS_IOS_DEVICE_TOKEN, IOS_DEVICE_TOKEN); params.put(USERS_ANDROID_DEVICE_TOKEN, ANDROID_DEVICE_TOKEN); StringBuilder postData = new StringBuilder(); for (Map.Entry<String, Object> param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); try { postData.append(URLEncoder.encode(param.getKey(), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } postData.append('='); try { postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } byte[] postDataBytes; postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); try { URL url; url = new URL(TABLES_PATH + "m-signup.php?"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setConnectTimeout(20000); conn.setReadTimeout(20000); conn.setDoInput(true); conn.setDoOutput(true); conn.getOutputStream().write(postDataBytes); // Get response if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream responseStream = new BufferedInputStream(conn.getInputStream()); BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream)); String line = ""; StringBuilder stringBuilder = new StringBuilder(); while ((line = responseStreamReader.readLine()) != null) { stringBuilder.append(line).append("\n"); } responseStreamReader.close(); String response = stringBuilder.toString(); responseStream.close(); conn.disconnect(); Log.i(TAG, "XSSignUp -> RESPONSE: " + response + "\n-----------------\n"); if (response.equals("e_101")) { return E_101; } else if (response.equals("e_102")) { return E_102; } else { return response; } // error } else { return "Something went wrong. Try again."; } } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } } This is how I call that function: final String sup = XSSignUp(usernameTxt.getText().toString(), passwordTxt.getText().toString(), emailTxt.getText().toString(), ""); Log.i(TAG, "SUP: " + sup); // errors if (sup.matches("e_101")) { hideHUD(); simpleAlert(E_101, ctx); } else if (sup.matches("e_102")) { hideHUD(); simpleAlert(E_102, ctx); } else { Log.i(TAG, "YES, SIGN UP!"); } So, if I run my app and fill a signup form using johndoe as username, my PHP script returns a response string as "e_101" (username already exists), and it prevents the script to add records to my database. I get this message in the Logcat: I/log-: XSSignUp -> RESPONSE: e_101 I/log-: SUP: e_101 I/log-: YES, SIGN UP! Which is wrong, because I shouldn't get the last line: I/log-: YES, SIGN UP!. This compromises my app because instead of firing an alert dialog (simpleAlert(E_101, ctx);), it goes on and skips that part. I don't really understand why the IF statement doesn't work, because I've also tried to do this: final String sup = XSSignUp(usernameTxt.getText().toString(), passwordTxt.getText().toString(), emailTxt.getText().toString(), ""); sup = "e_101"; <-- FORCING THE sup STRING TO BE "e_101"! // errors if (sup.matches("e_101")) { hideHUD(); simpleAlert(E_101, ctx); } else if (sup.matches("e_102")) { hideHUD(); simpleAlert(E_102, ctx); } else { Log.i(TAG, "YES, SIGN UP!"); } and then it works! But it doesn't make any sense to me since the sup string is the same as the one that my function returns from the PHP script, as you can see by the Logcat messages... I've also tried using equals(): sup.equals("e_101") No positive result, so what am I doing wrong?
Your response contains extra new line \n, that's why if not work. The problem is in here: stringBuilder.append(line).append("\n"); Try to change it like below: int i = 0; while ((line = responseStreamReader.readLine()) != null) { if(i != 0) stringBuilder.append("\n"); stringBuilder.append(line); i++; } Or .... stringBuilder.replace(stringBuilder.lastIndexOf("\n"), stringBuilder.length(),""); String response = stringBuilder.toString(); Beside this as you change the CASE of your response to upper inside XSSignUp and compare with lower CASE outside, you have to use equalsIgnoreCase instead of equals like sup.equalsIgnoreCase("e_101")
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?
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; }
testing url connection java html
When I am testing the list of url's to see if the connection is "alive" or "dead", I run into this site: (www.abbapregnancy.org) then site is blank with no information. How can I make an if statement to test for sites like this? Feel free to comment or suggest ideas. My code is currently like this: try {// Test URL Connection URL url = new URL("http://www."+line); URLConnection conn = url.openConnection(); conn.setDoOutput(true); wr = new OutputStreamWriter(conn.getOutputStream()); wr.flush(); rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); while( !rd.ready() ) {} if( rd.ready()) { //write to output file System.out.println("Good URL: " + line); urlAlive ++; //increment alive line to Alive url file aliveUrl += (line + System.getProperty("line.separator")); } else // increment dead url urlDead++; } catch (Exception e) // increment dead url { urlDead++; }
So you want to check more than just "alive" or "dead". If alive, you also want to know if the content is empty, right? Since you seem to want to check websites, using http connections makes sense here. For the alive/dead condition, connection attempts will throw an exception if dead. If alive, you can use the status code to check if the request was really successful. Finally, you can use the content-length header to check if the site is up but actually returning empty content. For example like this: public void checkURL(URL url) throws IOException { HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); System.out.println(String.format("Fetching %s ...", url)); try { int responseCode = conn.getResponseCode(); if (responseCode == 200) { System.out.println(String.format("Site is up, content length = %s", conn.getHeaderField("content-length"))); } else { System.out.println(String.format("Site is up, but returns non-ok status = %d", responseCode)); } } catch (java.net.UnknownHostException e) { System.out.println("Site is down"); } }
public static boolean IsReachable(Context context, String check_url) { // First, check we have any sort of connectivity final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo netInfo = connMgr.getActiveNetworkInfo(); boolean isReachable = false; if (netInfo != null && netInfo.isConnected()) { // Some sort of connection is open, check if server is reachable try { URL url = new URL(check_url); // URL url = new URL("http://192.168.100.93/office_com/www/api.php/office_com/Logins/SignUp?api_user=endpoint"); //URL url = new URL("http://10.0.2.2"); HttpURLConnection urlc = (HttpURLConnection) url.openConnection(); urlc.setRequestProperty("User-Agent", "Android Application"); urlc.setRequestProperty("Connection", "close"); urlc.setConnectTimeout(10 * 1000); try { urlc.connect(); System.out.println("-----fffff"); } catch (Exception e) { System.out.println("-----fffff " + e); } isReachable = (urlc.getResponseCode() == 200); } catch (IOException e) { } } return isReachable; }
Java PUT example please
I am attempting to send a user update to valance and I am looking for an example of how to do a put, specifically, a put to update a user. I have looked around but do not see an example of how to use the UserContext to send a json block using Java. Any pointers to documentation would be appreciated.
After tinkering with this, and with a great number of suggestions from my colleague (Who I am not sure wants to be identified so i will just call him Bill). We came up with the following Java method(should really be split into separate methods but it is understandable) private static String getValanceResult(ID2LUserContext userContext, URI uri, String query, String sPost, String sMethod, int attempts) { String sError = "Error: An Unknown Error has occurred"; if (sMethod == null) { sMethod = "GET"; } URLConnection connection; try { URL f = new URL(uri.toString() + query); //connection = uri.toURL().openConnection(); connection = f.openConnection(); } catch (NullPointerException e) { return "Error: Must Authenticate"; } catch (MalformedURLException e) { return "Error: " + e.getMessage(); } catch (IOException e) { return "Error: " + e.getMessage(); } StringBuilder sb = new StringBuilder(); try { // cast the connection to a HttpURLConnection so we can examin the // status code HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.setRequestMethod(sMethod); httpConnection.setConnectTimeout(20000); httpConnection.setReadTimeout(20000); httpConnection.setUseCaches(false); httpConnection.setDefaultUseCaches(false); httpConnection.setDoOutput(true); if (!"".equals(sPost)) { //setup connection httpConnection.setDoInput(true); httpConnection.setRequestProperty("Content-Type", "application/json"); //execute connection and send xml to server OutputStreamWriter writer = new OutputStreamWriter(httpConnection.getOutputStream()); writer.write(sPost); writer.flush(); writer.close(); } BufferedReader in; // if the status code is success then the body is read from the // input stream if (httpConnection.getResponseCode() == 200) { in = new BufferedReader(new InputStreamReader( httpConnection.getInputStream())); // otherwise the body is read from the output stream } else { in = new BufferedReader(new InputStreamReader( httpConnection.getErrorStream())); } String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } in.close(); // Determine the result of the rest call and automatically adjusts // the user context in case the timestamp was invalid int result = userContext.interpretResult( httpConnection.getResponseCode(), sb.toString()); if (result == ID2LUserContext.RESULT_OKAY) { return sb.toString(); // if the timestamp is invalid and we haven't exceeded the retry // limit then the call is made again with the adjusted timestamp } else if (result == userContext.RESULT_INVALID_TIMESTAMP && attempts > 0) { return getValanceResult(userContext, uri, query, sPost, sMethod, attempts - 1); } else { sError = sb + " " + result; } } catch (IllegalStateException e) { return "Error: Exception while parsing"; } catch (FileNotFoundException e) { // 404 return "Error: URI Incorrect"; } catch (IOException e) { } return sError; }
There is a php code snippet I can share from a project that uses the api (same rough logic with java). The User context just prepares the url and the framework of the specific environment (java runtime, or php library) is used to do the post and retrieve the results (in this case it is using php CURL). $apiPath = "/d2l/api/le/" . VERSION. "/" . $courseid . "/content/isbn/"; $uri = $opContext->createAuthenticatedUri ($apiPath, 'POST'); $uri = str_replace ("https", "http", $uri); curl_setopt ($ch, CURLOPT_URL, $uri); curl_setopt ($ch, CURLOPT_POST, true); $response = curl_exec ($ch); $httpCode = curl_getinfo ($ch, CURLINFO_HTTP_CODE); $contentType = curl_getinfo ($ch, CURLINFO_CONTENT_TYPE); $responseCode = $opContext->handleResult ($response, $httpCode, $contentType); $ret = json_decode($response, true); if ($responseCode == D2LUserContext::RESULT_OKAY) { $ret = "$response"; $tryAgain = false; } elseif ($responseCode == D2LUserContext::RESULT_INVALID_TIMESTAMP) { $tryAgain = true; } elseif (isset ($ret['Errors'][0]['Message'])) { if ($ret['Errors'][0]['Message'] == "Invalid ISBN") { $allowedOrgId[] = $c; } $tryAgain = false; } A sample of a trace of a post message is: PUT https://valence.desire2learn.com/d2l/api/lp/1.0/users/3691?x_b=TwULqrltMXvTE8utuLCN5O&x_a=L2Hd9WvDTcyiyu5n2AEgpg&x_d=OKuPjV-a0ZoSBuZvJkQLpFva2D59gNjTMiP8km6bdjk&x_c=UjCMpy1VNHsPCJOjKAE_92g1YqSxmebLHnQ0cbhoSPI&x_t=1336498251 HTTP/1.1 Accept-Encoding: gzip,deflate Accept: application/json Content-Type: application/json { "OrgDefinedId": "85033380", "FirstName": "First", "MiddleName": "Middle", "LastName": "Last", "ExternalEmail": "me#somehostname.com", "UserName": "Username", "Activation": { "IsActive": true } }