I'm trying to create a Foursquare application using its Java API v2 but I couldn't find any sample source code for the checkin process. I don't need to full source code (authentication, venue search, etc), I just need to checkin part.
Can somebody help me?
import java.net.*;
import java.io.*;
class HelloCheckin {
public static void main(String[] args) {
try {
// Construct data
String data = URLEncoder.encode("ll", "UTF-8") + "=" + URLEncoder.encode("53.576317,0.113386", "UTF-8");
data += "&" + URLEncoder.encode("venueId", "UTF-8") + "=" + URLEncoder.encode("4e144a2cc65bedaeefbb824a", "UTF-8");
data += "&" + URLEncoder.encode("oauth_token", "UTF-8") + "=" + URLEncoder.encode("YOUR_OAUTHTOKEN", "UTF-8");
// Send data
URL url = new URL("https://api.foursquare.com/v2/checkins/add");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
// Process line...
}
wr.close();
rd.close();
} catch (Exception e) {
}
} }
The body of this code came from Simple Java Post
Related
I'm trying to send a POST request to grab comments but it doesn't work in Java while it does work with postman.
I get an 403 Forbidden error, but on postman it retrieves the data i need just fine..
Here's the Java code I'm trying to use to replicate the behavior.
String targetUrl = YOUTBE_COMMENTS_AJAX_URL;
String urlParameters = "action_load_comments=1&order_by_time=True&filter=jBjXVrS8nXs";
String updatedURL = targetUrl + "?" + urlParameters;
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(updatedURL);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("content-type", "multipart/form-data");
urlConnection.setRequestProperty("user-agent", "USER_AGENT");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("video_id", "UTF-8")
+ "=" + URLEncoder.encode(youtubeId, "UTF-8");
data += "&" + URLEncoder.encode("session_token", "UTF-8") + "="
+ URLEncoder.encode(xsrfToken, "UTF-8");
data += "&" + URLEncoder.encode("page_token", "UTF-8") + "="
+ URLEncoder.encode(pageToken, "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String result = reader.readLine();
return result;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
Here's an example of what postman is sending in their headers
It seems like your problem is here (see inline comments):
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(urlParameters);
// you wrote your URL parameters into Body
wr.flush();
wr.close();
//You closed your body and told server - you are done with request
conn.getOutputStream().write(postDataBytes);
// you wrote data into closed stream - server does not care about it anymore.
You have to append your urlParameters directly to the URL when you open it
Then you have to write your Form Data into body as you do:
conn.getOutputStream().write(postDataBytes);
and then close output stream
I want the get some data from my database on my android application. This is my code:
try{
String nome = (String)arg0[0];
String stato = (String)arg0[1];
String link="http://www.example.org/AndroidPage.php";
String data = URLEncoder.encode("nome", "UTF-8") + "=" + URLEncoder.encode(nome, "UTF-8");
data += "&" + URLEncoder.encode("stato", "UTF-8") + "=" + URLEncoder.encode(stato, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("exception: " + e.toString());
}
If I comment the BufferReader statement I don't get any error. Here is the error..
(The file exist in the server)
http://i.stack.imgur.com/mb3sc.png
UPDATE:
I resolved the problem.. The error was inside the php script, I forgot to write a semicolon.
Did you add the Internet permission to the manifest?
<uses-permission android:name="android.permission.INTERNET" />
I understand Java but am completely inexperienced with connecting to web applications. How would I take the following HTTP POST request and make it JSON? The overall purpose is to send information from a Java application to an online Ruby on Rails SQLite3 database.
import java.io.*;
import java.net.*;
public class HTTPPostRequestWithSocket {
public void sendRequest() {
try {
String params = URLEncoder.encode("param1", "UTF-8") + "="
+ URLEncoder.encode("value1", "UTF-8");
params += "&" + URLEncoder.encode("param2", "UTF-8") + "="
+ URLEncoder.encode("value2", "UTF-8");
String hostname = "nameofthewebsite.com";
int port = 80;
InetAddress addr = InetAddress.getByName(hostname);
Socket socket = new Socket(addr, port);
String path = "/nameofapp";
// Send headers
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0rn");
wr.write("Content-Length: " + params.length() + "rn");
wr.write("Content-Type: application/x-www-form-urlencodedrn");
wr.write("rn");
// Send parameters
wr.write(params);
wr.flush();
// Get response
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
wr.close();
rd.close();
socket.close(); // Should this be closed at this point?
} catch (Exception e) {
e.printStackTrace();
}
}
}
I have a bash script when I logged in a web page to then parse the html. The command that I've used is wget:
wget --save-cookies=cookies.txt --post-data "uid=USER&pass=PWD" http://www.spanishtracker.com/login.php
wget --load-cookies=cookies.txt "http://www.spanishtracker.com/torrents.php" -O OUTPUT
Now, I'm trying to make these with Java. Firs of all, I'm trying to POST the request but when I execute the output don't gives as I was logged. These is the code of Java:
try {
data = URLEncoder.encode("uid", "UTF-8") + "=" + URLEncoder.encode("USER", "UTF-8");
data += "&" + URLEncoder.encode("pass", "UTF-8") + "=" + URLEncoder.encode("PASS", "UTF-8");
// Send the request
URL url = new URL("http://www.spanishtracker.com/index.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//write parameters
writer.write(data);
writer.flush();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
// temporary to build request cookie header
StringBuilder sb = new StringBuilder();
// find the cookies in the response header from the first request
List<String> cookies = conn.getHeaderFields().get("Set-Cookie");
if (cookies != null) {
System.out.println("Hay cookies para guardar");
for (String cookie : cookies) {
if (sb.length() > 0) {
sb.append("; ");
}
// only want the first part of the cookie header that has the value
String value = cookie.split(";")[0];
sb.append(value);
}
}
Could you help me please.
Many thanks and sorry for my english!
Use apache HttpClient library link
I am trying to write the following section of php code in java. I will provide the php code and the java code. What I would like help with is a) am I even on the right track and b) the line with the "Please help here" comment, I am unsure of how to do this in java. This line is header("Location: ".$strCitiRedirectURL.$content."");
Thank you in advance.
php code:
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "returning");
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
/* No UUID. Login to CITI failed. We may need a new user */
}elseif ($content == "- error: learner not affiliated with institution, add learner or provide username and password"){
// Resubmit as a new user
/* Package data up to post to CITI */
$req =& new HTTP_Request($strCitiLoginURL);
$req->setMethod(HTTP_REQUEST_METHOD_POST);
$req->addPostData("instusername", $strInstUsername);
$req->addPostData("institution", $strInstitution);
$req->addPostData("key", $strInstitutionKey);
$req->addPostData("type", "new");
$req->addPostData("first", $strFirst);
$req->addPostData("last", $strLast);
$req->addPostData("email", $strEmail);
$response = $req->sendRequest();
if(isset($_GET['showDebug'])){
print $req->_buildRequest();
}
if (PEAR::isError($response)) {
$content = $response->getMessage();
} else {
$content = $req->getResponseBody();
}
/* Check for 44 Character UUID */
if (preg_match($pattern,$content)){
print 'Success';
ob_start();
/*PLEASE HELP ON THIS LINE*/ header("Location: ".$strCitiRedirectURL.$content."");
ob_flush();
}else{
$errMsg = $errMsg.' <li>CITI Error Returned: '.$content.'.</li>';
}
java code
//****CITI CONFIGURATION****
final String pattern = "([0-9A-\\-]{44})";
final String CitiRedirectUrl = "https://www.citiprogram.org/members/mainmenu.asp?strKeyID=";
final String CitiLoginUrl = "http://www.citiprogram.org/remoteloginII.asp";
//****END CITI CONFIGURATION****
try {
// Construct data
String data = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
data += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
data += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
URL url = new URL("http://www.citiprogram.org/remoteloginII.asp");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
if (pregMatch(pattern, line)) {
//Do the header part from the php code
} else if (line.equals("- error: learner not affiliated with institution, add learner or provide username and password")) {
// Resubmit as a new user
/* Package data up to post to CITI */
// Construct data
String newdata = URLEncoder.encode("instusername", "UTF-8") + "=" + URLEncoder.encode(c_form.getCan(), "UTF-8");
newdata += "&" + URLEncoder.encode("institution", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
newdata += "&" + URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode("returning", "UTF-8");
// Send data
OutputStreamWriter newwr = new OutputStreamWriter(conn.getOutputStream());
newwr.write(data);
newwr.flush();
// Get the response
BufferedReader newrd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String newline;
while ((newline = newrd.readLine()) != null) {
System.out.println(newline);
if (pregMatch(pattern, newline)) {
} else {
//Print error message
}
}
}
}
wr.close();
rd.close();
} catch (Exception e) {
}
//Check for 44 character UUID
public static boolean pregMatch(String pattern, String content) {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(content);
boolean b = m.matches();
return b;
}
I believe
header("Location: ".$strCitiRedirectURL.$content."");
in PHP would be the same as the following in Java (using your wr object):
wr.sendRedirect("http://path.to.redirect/");
You could also forward the request, but I have a feeling you just want the client to redirect to citirewards or whatever, in which case sendRedirect is the solution.
EDIT: Source - http://docs.oracle.com/javaee/1.3/api/javax/servlet/http/HttpServletResponse.html#sendRedirect(java.lang.String)