PHP to test Java class(about post data to web) - java

I wrote a program to send a String to Web URL, but before sending i need to test it use PHP on localhost. I never learn PHP. So would you guys help me out?
public class MessageSender {
public static Boolean sendMsg(String outboundUrl,String message) {
Boolean sendResult = false;
URL url;
HttpURLConnection connection = null;
try {
message = URLEncoder.encode("message", "UTF-8");
//Create connection
url = new URL(outboundUrl);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" +
Integer.toString(message.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches (false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (message);
wr.flush ();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
wr.close ();
rd.close();
String Whole=response.toString();
//System.out.println(Whole);
sendResult = true;
}
catch (Exception e) {
e.printStackTrace();
return sendResult;
}
finally {
if(connection != null) {
connection.disconnect();
}
}
return sendResult;
}
}
I do not know what to do to test use PHP on localhost

If you have installed php , make some folder ie /tmp/phppublic and place a index.php file there
PHP Server
index.php
<?php
var_dump($_POST);
?>
Console
cd /tmp/phppublic
php -S localhost:8000
To test your Java set
outboundUrl = "http://localhost:8000/index.php"

Related

Java Bitstamp API market order File not Found

I am trying to make a post from Java to make a market order using my Bitstamp account but the following code is returning a file not found for the URL.
It may be because of CSRF but I am unsure, if anyone has had any experience with the bitstamp API that would be great.
public static void postToken() throws IOException, JSONException {
URL url = null;
String sig = encode();
try {
url = new URL("https://www.bitstamp.net/api/v2/buy/market/" + feedbackType.toLowerCase() +"usd/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);//5 secs
connection.setReadTimeout(5000);//5 secs
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
JSONObject cred = new JSONObject();
cred.put("key",api_key);
cred.put("signature", sig);
cred.put("nonce", nonce);
cred.put("amount", feedback);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(cred.toString());
out.flush();
out.close();
int res = connection.getResponseCode();
System.out.println(res);
InputStream is = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine() ) != null) {
Log.d(TAG, line);
}
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
Error: W/System.err: java.io.FileNotFoundException: https://www.bitstamp.net/api/v2/buy/market/btcusd/

Trying to get an Access Token from Dwolla restful api

Im having trouble getting an access token for the sandbox environment.
Im following this guide for authenticating: OAuth
So when i create my request, following this guide, i get the following response from the api:
{"error":"access_denied","error_description":"Invalid application credentials."}
Im using key for mf client ID and secret as my client secret as per the instructions.
Here is the code Im using:
public static void main(String[] args) {
try {
URL url = new URL("https://www.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("client_id", "<Key>");
conn.setRequestProperty("client_secret", "<Secret>");
conn.setRequestProperty("grant_type", "client_credentials");
conn.setDoInput(true);
conn.setDoOutput(true);
System.out.println("Message:" + conn.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(PaymentTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
I was able to get an access token finally. My problem is first of all the above code uses client_id and client_secret as header params. These need to go in the body of the request.
My second problem is that I used the wrong content type for the message I was sending.
Here is the code that worked for me:
URL url = new URL("https://sandbox.dwolla.com/oauth/v2/token");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String data = "";
JSONObject jsonObj = new JSONObject();
jsonObj.put("client_id", "<Your Client ID>");
jsonObj.put("client_secret", "<Your Client Secret>");
jsonObj.put("grant_type", "client_credentials");
data = jsonObj.toString();
System.out.println("data = " + data);
byte[] outputInBytes = data.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.close();
System.out.println("Message:" + conn.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();

HttpURLConnection always failing with 401

I'm trying to use HttpURLConnection for connecting to server from Android app which I'm developing. For now, I'm testing the connection code not in an app but as a plain java program with main class. I guess this doesn't make any difference as far as HttpUrlConnection.
Please examine the code snippet. Another issue is even errorStream is throwing null. This I feel is because of malformed URL.
private static String urlConnectionTry() {
URL url; HttpURLConnection connection = null;
try {
String urlParameters = "email=" + URLEncoder.encode("email", "UTF-8") +
"&pwd=" + URLEncoder.encode("password", "UTF-8");
//Create connection
url = new URL("http://example.com/login");
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("uuid", getUuid());
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setInstanceFollowRedirects(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
InputStream is = connection.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if(connection != null) {
connection.disconnect();
}
}
}
private static String getUuid() {
try {
Document doc=Jsoup.connect("http://example.com/getUuid").get();
Elements metaElems = doc.select("meta");
for (Element metaElem : metaElems) {
if(metaElem.attr("name").equals("uuid")) {
return metaElem.attr("content");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
You're probably receiving 401 because the credentials that was sent to the server is not authorized- it's probably not registered or the password is incorrect.
As for the null error stream, take a look at this SO answer.
If the connection was not connected, or if the server did not have an error while connecting or if the server had an error but no error data was sent, this method will return null.
It is probably better if you check first the response code using HttpUrlConnection#getResponseCode(). Decide on whether you'll be checking the contents of the error stream based on the response code you get.

Java code to login to website which contains emailId in page and password in another page

I want to write a Java application, which can login to a website For example, www.tumblr.com/login. Basically this web page asks for an email address on the first page and then would take the user to the next page to enter the password.
Can someone please help me with a sample Java code for this problem?
You might want to look at HttpURLConnection
public static String executePost(String targetURL, String urlParameters) {
HttpURLConnection connection = null;
try {
//Create connection
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (
connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
Code example found here

How to send and receive data between Android and GAE-python

I am using this code to send data to the site where my gae-python app is deployed .But I dont know how to receive it on the other end.
protected void tryLogin(String mUsername, String mPassword)
{
HttpURLConnection connection;
OutputStreamWriter requestself = null;
URL url = null;
String response = null;
String parameters = "username="+mUsername+"&password="+mPassword;
try
{
url = new URL("http://www.pranshutrial3.appspot.com");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
requestself = new OutputStreamWriter(connection.getOutputStream());
requestself.write(parameters);
requestself.flush();
requestself.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after login process will be stored in response variable.
response = sb.toString();
// You can perform UI operations here
Toast.makeText(this,"Message from Server: \n"+ response, Toast.LENGTH_LONG).show();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
}

Categories

Resources