Ive looked at a lot of other threads here and all over the internet and I cant seem to solve this..
So basically I have written this Java code:
public void sendReport(CommandSender sender, Player target, String reason)
{
HttpURLConnection connectionStandard = null;
String email = config.getString("rp.site.email");
String password = config.getString("rp.site.password");
String senderName = sender.getName();
String targetName = target.getDisplayName();
String reasonString = reason;
try
{
URL url = new URL("http://www.website.net/folder/connect.php");
HttpURLConnection request = (HttpURLConnection)url.openConnection();
request.setRequestProperty("Content-type","application/x-www-form-urlencoded");
request.setRequestMethod("POST");
request.setDoOutput(true);
OutputStreamWriter post = new OutputStreamWriter(request.getOutputStream());
String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email.toString(), "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password.toString(), "UTF-8");
data += "&" + URLEncoder.encode("reporter", "UTF-8") + "=" + URLEncoder.encode(senderName, "UTF-8");
data += "&" + URLEncoder.encode("reported", "UTF-8") + "=" + URLEncoder.encode(targetName, "UTF-8");
data += "&" + URLEncoder.encode("reason", "UTF-8") + "=" + URLEncoder.encode(reasonString, "UTF-8");
post.write(data);
post.flush();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
} finally
{
if(null != connectionStandard)
{
connectionStandard.disconnect();
}
}
}
and basically, my php code just looks like this:
<?php
require_once "db.php";
$reporter->startSecureSession();
foreach ($_POST as $post => $value) {
$post = strip_tags($post);
$value = strip_tags($value);
}
if(!(isset($_POST['email'])) or (!isset($_POST['password'])) or (!isset($_POST['reporter'])) or (!isset($_POST['reported'])) or (!isset($_POST['reason']))) {
exit("Invalid Request");
}
$password = hash("sha512", $_POST['password']);
$reporter->login(array("email" => $_POST['email'], "password" => $password), "plugin");
if($reporter->validateClient()) {
$reporter->sendReport($_POST);
header("Location: logout.php");
exit();
} else {
exit();
}
?>
When I send my details through chrome to the web page, it works and sends stuff to my database, but when I do it off my bukkit server through the command that sends the request, it doesnt :/
Thanks for the help :)
You can use Apache httpclient 4.x to send GET/POST request from Java.
String url = "http://www.website.net/folder/connect.php";
HttpPost method = new HttpPost(url);
HttpClient httpClient = new DefaultHttpClient();
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams.add(new BasicNameValuePair("email", email.toString()));
formparams.add(new BasicNameValuePair("password", password.toString()));
formparams.add(new BasicNameValuePair("reporter", senderName));
formparams.add(new BasicNameValuePair("reported", targetName));
formparams.add(new BasicNameValuePair("reason", reasonString));
UrlEncodedFormEntity entity = null;
try {
entity = new UrlEncodedFormEntity(formparams, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
method.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(method);
Well, from the javadoc of URLConnection:
1) The connection object is created by invoking the openConnection method
on a URL.
2) The setup parameters and general request properties are
manipulated.
3) The actual connection to the remote object is made, using
the connect method.
4) The remote object becomes available. The header
fields and the contents of the remote object can be accessed.
You do not appear to have called URLConnection#connect.
Related
I want to know if there is an error response when sending the REST POST request, and i want to print the error as "output" in my Java application.
How do i do this?
Here is the code I'm using:
HttpClient client = new HttpClient();
try {
HttpPost request = new HttpPost("example.com/api/deposit");
StringEntity params;
params = new StringEntity("{"
+ "\"locale\": \"" + exampleclass.getLocale() + "\","
+ "\"dateFormat\": \"" + exampleclass.getDateFormat() + "\","
+ "\"transactionDate\": \"" + exampleclass.getTransactionDate() + "\","
+ "\"transactionAmount\": \"" + exampleclass.getTransactionAmount() + "\","
+ "}");
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept-Language", "en-US,en;q=0.8");
request.addHeader("Authorization", "Basic somecode&&!!");
request.setEntity(params);
HttpResponse response = client.execute(request);
//handle the response somehow
//example : System.out.println (errormessage);
} catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
} finally {
client.getConnectionManager().shutdown();
}
Any help is greatly appreciated!
You should be able to read the returned HTTP status code in the HttpResponse response.
response.getStatusLine().getStatusCode()
return the HTTP code, 200 means OK, another code indicate error.
You can use something as below:-
String line = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(getResponse.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
System.out.println(line);
}
I'm trying to set the OAuth Authorization header of a HttpsURLConnection object and below is the java code for that
String url1 = "/data/ServiceAccount?schema=1.0&form=json&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String url = "https://secure.api.abc.net/data/ServiceAccount?schema=1.0&byBillingAccountId={EQUALS,xyz#pqr.edu}";
String header = OAuthClient.prepareURLWithOAuthSignature(url1);
HttpsURLConnection con = null;
try {
URL obj = new URL(url);
con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Authorization", "OAuth " + header);
System.out.println("Request properties = " + con.getRequestProperty("Authorization"));
int responseCode = con.getResponseCode();
System.out.println("Response Code = " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
con.disconnect();
//print result
System.out.println("Response = " + response.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(con!=null) con.disconnect();
}
And below is the code for prepareURLWithOAuthSignature
public String prepareURLWithOAuthSignature(String url)
{
String signature = null;
setOAuthParameters();
setOAuthQParams();
try
{
httpURL = URLEncoder.encode(baseURL+url, "UTF-8");
signature = OAuthSignatureService.getSignature(httpURL, URLEncoder.encode(URLEncodedUtils.format(qparams, "UTF-8"), "UTF-8"), consumer_secret);
OAuthParameters.put("oauth_signature", signature);
} catch (Exception e) {
e.printStackTrace();
}
return getOAuthAuthorizationHeader();
}
public String getOAuthAuthorizationHeader()
{
String OAuthHeader = "oauth_consumer_key=\"" + OAuthParameters.get("oauth_consumer_key") + "\"" +
",oauth_signature_method=\"" + OAuthParameters.get("oauth_signature_method") + "\"" +
",oauth_timestamp=\"" + OAuthParameters.get("oauth_timestamp") + "\"" +
",oauth_nonce=\"" + OAuthParameters.get("oauth_nonce") + "\"" +
",oauth_version=\"" + OAuthParameters.get("oauth_version") + "\"" +
",oauth_signature=\"" + OAuthParameters.get("oauth_signature") + "\"";
byte[] authEncBytes = Base64.encodeBase64(OAuthHeader.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
The problem is that
1) while I'm printing the con.getRequestProperty("Authorization") I'm getting a null value which means the Authorization header is not set
2) The final response I'm getting from the server is 403
Any idea what's going wrong here?
I know this might not be an answer but looks like this issue was submitted as a bug to sun and here is the relevant part of the reply.
This behavior is intentional in order to prevent a security hole that
getRequestProperty() opened. setRequestProperty("Authorization")
should still work, you just won't be able to proof the results via
getRequestProperty().
For the original forum post, please see: http://www.coderanch.com/t/205485/sockets/java/setRequestProperty-authorization-JDK
I would not be able to advice why you're getting a 403 but try adding the "Content-Type" request header to your connection and see if it makes any difference. Until I added that header in my code, I was getting a 404 back from the Spring Security module.
I use nodejs as server and java(android) as client,i succes send data through post from android to node. but my problem when android send the data (string) consist of space and new line (enter) its received on node but the character was change,
for example,i send this string from android
Hello
I learn android
the string send to node and received,but i get this in node
Hello%0AI+learn+android
I use this code for send string to node in android.
public void btnOnClick(){
String text= URLEncoder.encode(editText.getText().toString(), "utf-8"); //I get from editText and convert to utf-8
sendToNode(text);
}
public void sendToNode(String text){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myDomain.com:8888/");
UrlEncodedFormEntity form;
try {
Log.i("kirim ke node isitextAsli ",text);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datanah",text));
form=new UrlEncodedFormEntity(nameValuePairs,"UTF-8");
httppost.setEntity(form);
HttpResponse response = httpclient.execute(httppost);
Log.i("HTTP Post", "Response from server node = " + response.getStatusLine().getReasonPhrase() + " Code = " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
Log.e("HTTP Post", "Protocol error = " + e.toString());
} catch (IOException e) {
Log.e("HTTP Post", "IO error = " + e.toString());
}
}
and I use this code for receive string in node
req.addListener('data', function(chunk) { data += chunk; });
req.addListener('end', function() {
console.log("from android :"+data); //result of data is Hello%0AI+learn+android
});
How i solve my problem?
please help,Thanks.
The string is URL-encoded, as you explicitly asked for in your code (and need for a regular POST). Decode it on the server.
To decode it on the server side, do:
var querystring = require('querystring');
querystring.unescape(data.replace(/\+/g, " "));
The following is the sample of encoding and decoding, YOU WANT TO DECODE IN THE SERVER PART
String encoded;
try {
encoded = URLEncoder.encode(input, "UTF-8");
System.out.println("URL-encoded by client with UTF-8: " + encoded);
String incorrectDecoded = URLDecoder.decode(encoded, "ISO-8859-1");
System.out.println("Then URL-decoded by server with ISO-8859-1: " + incorrectDecoded);
String correctDecoded = URLDecoder.decode(encoded, "UTF-8");
System.out.println("Server should URL-decode with UTF-8: " + correctDecoded);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So I'm writing a small app to dump a directory of images into the user's tumblr blog, using their provided API: http://www.tumblr.com/docs/en/api
I've gotten plaintext posting to work, but now I need to find out how to send an image file in the POST instead of UTF-8 encoded text, and I'm lost. My code at the moment is returning a 403 forbidden error, as if the username and password were incorrect (they're not), and everything else I try gives me a bad request error. I'd rather not have to use external libraries for this if I can. This is my ImagePost class:
public class ImagePost {
String data = null;
String enc = "UTF-8";
String type;
File img;
public ImagePost(String imgPath, String caption, String tags) throws IOException {
//Construct data
type = "photo";
img = new File(imgPath);
data = URLEncoder.encode("email", enc) + "=" + URLEncoder.encode(Main.getEmail(), enc);
data += "&" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc);
data += "&" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc);
data += "&" + URLEncoder.encode("data", enc) + "=" + img;
data += "&" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc);
data += "&" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8");
data += "&" + URLEncoder.encode("tags", "UTF-8") + "=" + URLEncoder.encode(tags, "UTF-8");
}
public void send() throws IOException {
// Set up connection
URL tumblrWrite = new URL("http://www.tumblr.com/api/write");
HttpURLConnection http = (HttpURLConnection) tumblrWrite.openConnection();
http.setDoOutput(true);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type", "image/png");
DataOutputStream dout = new DataOutputStream(http.getOutputStream());
//OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());
// Send data
http.connect();
dout.writeBytes(data);
//out.write(data);
dout.flush();
System.out.println(http.getResponseCode());
System.out.println(http.getResponseMessage());
dout.close();
}
}
I suggest you use MultipartRequestEntity (successor of deprecated MultipartPostMethod) of the Apache httpclient package. With MultipartRequestEntity you can send a multipart POST request including a file. An example is below:
public static void postData(String urlString, String filePath) {
log.info("postData");
try {
File f = new File(filePath);
PostMethod postMessage = new PostMethod(urlString);
Part[] parts = {
new StringPart("param_name", "value"),
new FilePart(f.getName(), f)
};
postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
HttpClient client = new HttpClient();
int status = client.executeMethod(postMessage);
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I have problem with authentication GReader editing API. I can do the HTTPS (https://www.google.com/accounts/ClientLogin) for authentication and google is returning three tokens (SID, LSID, AUTH), but no HSID.
When I try add a new feed http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll with POST data T=djj72HsnLS8293&quickadd=blog.martindoms.com/feed/ without HSID in Cookie, is response status code 401. With SID and HSID in Cookie everything works properly.
What is and where can I find this HSID string?
Thaks for your answers.
My code:
public void addNewFeed() throws IOException {
HttpPost requestPost = new HttpPost("http://www.google.com/reader/api/0/subscription/quickadd?ck=1290452912454&client=scroll");
getSid();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
DefaultHttpClient client = new DefaultHttpClient();
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
try {
nameValuePairs.add(new BasicNameValuePair("T", _token));
nameValuePairs.add(new BasicNameValuePair("quickadd", "blog.martindoms.com/feed/"));
requestPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(requestPost);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
System.out.println(str.toString());
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Looks like you might be using old info as a reference. Google switched to using auth now.
You'll need to replace getSid() with a getAuth() function.
Then this line
requestPost.addHeader("Cookie", "SID=" + _sid + "; HSID=" + _hsid);
should now be this
requestPost.addHeader("Authorization", "GoogleLogin auth=" + _auth);