How to create a hastebin with java - java

I need to create a hastebin paste in java, but I don't know how.
I tried this
public static String paste(String content) throws MalformedURLException, IOException {
URL url = new URL("https://hasteb.in/documents");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection) con;
http.addRequestProperty("data", content);
http.setRequestMethod("POST");
http.setDoOutput(true);
InputStream in = new BufferedInputStream(http.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder entirePage = new StringBuilder();
String inputLine;
while ((inputLine = reader.readLine()) != null) {
entirePage.append(inputLine);
}
reader.close();
if (!(entirePage.toString().contains("\"key\":\""))) {
return "UNKNOWN";
}
return "https://hasteb.in/"+entirePage.toString().split("\"key\":\"")[1].split("\",")[0];
}
But it does not work.
Error is Caused by: java.lang.IllegalArgumentException: Illegal character(s) in message header value
Any help?

To do a POST request using HttpURLConnection you need to write the request body using the provided OutputStream functionality rather than setting a HTTP header named "data":
try (OutputStream out = http.getOutputStream()) {
out.write(content.getBytes());
out.flush();
}
This needs to happen BEFORE you start reading from the InputStream (and I would suggest using try-with-resources for that as well).

Related

Getting unknown protocol error when trying to POST to endpoint

I am trying to connect to an endpoint using a post method however I keep getting the following error:
java.net.MalformedURLException: unknown protocol: localhost
at java.base/java.net.URL.<init>(URL.java:634)
at java.base/java.net.URL.<init>(URL.java:523)
at java.base/java.net.URL.<init>(URL.java:470)
at endpointtest.endpoint(endpointtest.java:23)
at main.main(endpoint.java:66)
I would expect my code to return the response based on the post request however that is not the case. Below is my code:
public class endpointtest {
public String endpoint(String urlStr, String username) {
final StringBuilder response = new StringBuilder();
try {
//creating the connection
URL url = new URL(urlStr);
HttpClient client = HttpClient.newHttpClient();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "Value");
connection.connect();
//builds the post body, adds parameters
final DataOutputStream out = new DataOutputStream(connection.getOutputStream());
//out.writeBytes(toJSON(globalId));
out.flush();
out.close();
//Reading the response
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputline;
while ((inputline = in.readLine()) != null) {
response.append(inputline);
}
in.close();
connection.getResponseCode();
connection.disconnect();
} catch (final Exception ex) {
ex.printStackTrace();
System.out.println(" error ");
}
return response.toString();
}
}
class main {
public static void main(String[] args){
endpointtest ep = new endpointtest();
ep.endpoint("localhost:8080/endpoint","123");
}
}
Why is this error occuring? Forgive me if there are basic errors, I am new to web dev
you have not included protocol(http/https) in your URL string.
Change it to ep.endpoint("http://localhost:8080/endpoint", "123");
and it should work.

Why am I receiving Error 400 BAD Request when sending data to online hosting?

I'm developing an Android software where it passes the data from mobile to Web via REST API Post method, I'm currently encountering BAD Request when I'm sending a parameter "5%5%". I tried to send it to my localhost using XAMPP and it doesn't give "ERROR 400 Bad Request"
This is how I send my data
JSONObject jsonObject = jParser.makeRequest("POST", "http://"+ MyHelper.getStrOnline()+MyHelper.getUrlUpload(), params);
This is the code I got from some other posts on how to send data to RESTful API
public JSONObject makeRequest(String method, String url, Map<String, String> stringMap) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
JSONObject jOBJ = null;
urlConnection = (HttpURLConnection) makeURLConnectionRequest(method, url, stringMap);
InputStream inputStream;
urlConnection.setConnectTimeout(5000000);
urlConnection.setReadTimeout(5000000);
// get stream
if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
inputStream = urlConnection.getInputStream();
} else {
inputStream = urlConnection.getErrorStream();
}
// parse stream
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String temp, response = "";
while ((temp = bufferedReader.readLine()) != null) {
response += temp;
}
jOBJ = new JSONObject(response);
return jOBJ;
}
public URLConnection makeURLConnectionRequest(String method, String apiAddress, Map<String, String> stringMap) throws IOException {
URL url = null;
url = new URL(apiAddress);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
String requestBody ="";
if(stringMap.size()!=0) {
requestBody = buildPostParameters(stringMap);
}
urlConnection.setReadTimeout(5000000);
urlConnection.setConnectTimeout(5000000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(!method.equals("GET"));
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
writer.write(requestBody);
writer.flush();
writer.close();
outputStream.close();
urlConnection.connect();
return urlConnection;
}

FileNotFoundException when loading API from URL. Java. Android

Im trying to return a JSON string from this api:
https://market.mashape.com/pareshchouhan/trivia
however Java is throwing the error:
java.io.FileNotFoundException: https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions?limit=10&page=1
On the line
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
I have used similar code with other Rest APIs so i am a bit unsure why this is happenning.
static String jsonStr;
String data = "";
#Override
protected Void doInBackground(Void... params) {
BufferedReader br = null;
try {
URL url;
String urlStr = "https://pareshchouhan-trivia-v1.p.mashape.com/v1/getAllQuizQuestions?limit=10&page=1";
url = new URL(urlStr);
URLConnection connection = url.openConnection();
connection.setRequestProperty("X-Mashape-Key", "4OFryNEYTWmshe8GheSnmIVEj7gZp1kJf6cjsncjVhXj9WYACn");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
jsonStr = sb.toString();
} catch (Exception e){
e.printStackTrace();
}
return null;
}
Any help would be greatly appreciated.
Regards.
Turns out I was trying to perform the wrong type of Request. This specific API did not support Get requests. Discovered this using https://www.hurl.it/
regardless, using the tutorial found here:
http://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/
I was able to change the request type and pull the correct data.
Hope this helps.

Java Put-Request returns 400 Bad Request

I try to perfom a put-request against a rest-api written by me, but it always returns 400-Bad Request.
java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8000/api/v0/contacts/2
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
I can call the url with firefox-rest client-plugin as well as another angular client, so I guess I have configured something wrong in my java code.
The server always returns something, so I don't know, why it crashes when I try to get the input stream.
protected String put(String path, String parameters)
throws IOException {
HttpURLConnection connection = getConnection(path, "PUT", parameters);
OutputStreamWriter outputWriter = new OutputStreamWriter(
connection.getOutputStream());
outputWriter.write(parameters);
outputWriter.flush();
outputWriter.close();
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String response = reader.readLine();
while(response != null){
response += reader.readLine();
}
reader.close();
return response;
}
private HttpURLConnection getConnection(String path, String method,String params) throws MalformedURLException, IOException,
ProtocolException {
URL url = new URL(this.api + path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Length",
String.valueOf(params.length()));
return connection;
}
Sorry for bad english, it's not my mother tongue.
I did ipconfig in cmd prompt and it showed 192.168.1.3. i changed it in the place of localhost in Android app and now i am able to access local web server.

Java HTTPS Client [duplicate]

I'm trying to find Java's equivalent to Groovy's:
String content = "http://www.google.com".toURL().getText();
I want to read content from a URL into string. I don't want to pollute my code with buffered streams and loops for such a simple task. I looked into apache's HttpClient but I also don't see a one or two line implementation.
Now that some time has passed since the original answer was accepted, there's a better approach:
String out = new Scanner(new URL("http://www.google.com").openStream(), "UTF-8").useDelimiter("\\A").next();
If you want a slightly fuller implementation, which is not a single line, do this:
public static String readStringFromURL(String requestURL) throws IOException
{
try (Scanner scanner = new Scanner(new URL(requestURL).openStream(),
StandardCharsets.UTF_8.toString()))
{
scanner.useDelimiter("\\A");
return scanner.hasNext() ? scanner.next() : "";
}
}
This answer refers to an older version of Java. You may want to look at ccleve's answer.
Here is the traditional way to do this:
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static String getText(String url) throws Exception {
URL website = new URL(url);
URLConnection connection = website.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null)
response.append(inputLine);
in.close();
return response.toString();
}
public static void main(String[] args) throws Exception {
String content = URLConnectionReader.getText(args[0]);
System.out.println(content);
}
}
As #extraneon has suggested, ioutils allows you to do this in a very eloquent way that's still in the Java spirit:
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();
try {
System.out.println( IOUtils.toString( in ) );
} finally {
IOUtils.closeQuietly(in);
}
Or just use Apache Commons IOUtils.toString(URL url), or the variant that also accepts an encoding parameter.
There's an even better way as of Java 9:
URL u = new URL("http://www.example.com/");
try (InputStream in = u.openStream()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
Like the original groovy example, this assumes that the content is UTF-8 encoded. (If you need something more clever than that, you need to create a URLConnection and use it to figure out the encoding.)
Now that more time has passed, here's a way to do it in Java 8:
URLConnection conn = url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
pageText = reader.lines().collect(Collectors.joining("\n"));
}
Additional example using Guava:
URL xmlData = ...
String data = Resources.toString(xmlData, Charsets.UTF_8);
Java 11+:
URI uri = URI.create("http://www.google.com");
HttpRequest request = HttpRequest.newBuilder(uri).build();
String content = HttpClient.newHttpClient().send(request, BodyHandlers.ofString()).body();
If you have the input stream (see Joe's answer) also consider ioutils.toString( inputstream ).
http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html#toString(java.io.InputStream)
The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)
If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.
Example
String result = getUrlAsString("https://www.google.com");
System.out.println(result);
outputs
<!doctype html><html itemscope="" .... etc
Code
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static String getUrlAsString(String url)
{
try
{
URL urlObj = new URL(url);
URLConnection con = urlObj.openConnection();
con.setDoOutput(true); // we want the response
con.setRequestProperty("Cookie", "myCookie=test123");
con.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
String newLine = System.getProperty("line.separator");
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine + newLine);
}
in.close();
return response.toString();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
Here's Jeanne's lovely answer, but wrapped in a tidy function for muppets like me:
private static String getUrl(String aUrl) throws MalformedURLException, IOException
{
String urlData = "";
URL urlObj = new URL(aUrl);
URLConnection conn = urlObj.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8)))
{
urlData = reader.lines().collect(Collectors.joining("\n"));
}
return urlData;
}
URL to String in pure Java
Example call to get payload from http get call
String str = getStringFromUrl("YourUrl");
Implementation
You can use the method described in this answer, on How to read URL to an InputStream and combine it with this answer on How to read InputStream to String.
The outcome will be something like
public String getStringFromUrl(URL url) throws IOException {
return inputStreamToString(urlToInputStream(url,null));
}
public String inputStreamToString(InputStream inputStream) throws IOException {
try(ByteArrayOutputStream result = new ByteArrayOutputStream()) {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
return result.toString(UTF_8);
}
}
private InputStream urlToInputStream(URL url, Map<String, String> args) {
HttpURLConnection con = null;
InputStream inputStream = null;
try {
con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(15000);
if (args != null) {
for (Entry<String, String> e : args.entrySet()) {
con.setRequestProperty(e.getKey(), e.getValue());
}
}
con.connect();
int responseCode = con.getResponseCode();
/* By default the connection will follow redirects. The following
* block is only entered if the implementation of HttpURLConnection
* does not perform the redirect. The exact behavior depends to
* the actual implementation (e.g. sun.net).
* !!! Attention: This block allows the connection to
* switch protocols (e.g. HTTP to HTTPS), which is <b>not</b>
* default behavior. See: https://stackoverflow.com/questions/1884230
* for more info!!!
*/
if (responseCode < 400 && responseCode > 299) {
String redirectUrl = con.getHeaderField("Location");
try {
URL newUrl = new URL(redirectUrl);
return urlToInputStream(newUrl, args);
} catch (MalformedURLException e) {
URL newUrl = new URL(url.getProtocol() + "://" + url.getHost() + redirectUrl);
return urlToInputStream(newUrl, args);
}
}
/*!!!!!*/
inputStream = con.getInputStream();
return inputStream;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Pros
It is pure java
It can be easily enhanced by adding different headers as a map (instead of passing a null object, like the example above does), authentication, etc.
Handling of protocol switches is supported

Categories

Resources