How to work with server response codes in java? - java

I am new to programming (especially in java) and I most likely lack knowledge with server work in java, my question is that I could send a request to the server and at the same time receive a response in the form of a response code, for example 404 (file not found), please someone tell me how to correctly implement this
the code we currently have
public static void Connection(int portNumber, String addr, String request) throws UnknownHostException, IOException {
URL url = new URL(addr);
String postData = request; // html request
int response = 0;
responses = response;
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", Integer.toString(postData.length()));
//<-------------------------------------Add a response code------------------------------------->//
try (DataOutputStream dos = new DataOutputStream(conn.getOutputStream())) {
dos.writeBytes(postData);
}
try (BufferedReader bf = new BufferedReader(new InputStreamReader(
conn.getInputStream())))
{
String line;
while ((line = bf.readLine()) != null) {
System.out.println(line);
}
}
}
Honestly. I've been scouring the internet and trying to find this in java books, but I haven't been able to find a proper answer

If you just want to send Http request and receive the data back you can just use 3d party Http clients. The most popular are Apache Http Client with good tutorial - Apache HttpClient Tutorial and OK Http client with good tutorial - A Guide to OkHttp. However, If you want to learn how to use Java classes such as URLConnection so you can write your own code than I can offer you to look at source code of my own Http client that I wrote using those classes. This HttpClient can also be used as 3d party Http client (although it is a simplistic and not well-known as the 3d party clients I mentioned above), but also you can look at the source code that is not that big and (I hope) is well and clearly written. So it could be used as tutorial as well. This HttpClient comes as part of MgntUtils Open Source library written and maintained by me. Here is the source code of HttpClient. Here is its Javadoc. If you want the source code of the whole library you can get it on Github here, and just the library as Maven artifact is available from Maven Central here

Related

What is the correct URL for Google's Cloud Speech API internet requests and how to request using java?

I'm simply using Eclipse IDE and Java to try to collect voice memos through a microphone, then turn that audio into text in real time. I'm not sure if I'm doing it right but if I send this URL the compiler give me a 403 error meaning it doesn't accept the key that I paste onto the URL. So my question is:
Does anyone happen to know why the URL connection is not taking my key? or which application restriction should I be using instead of NONE?
public class Recognizer {
/**
* URL to POST audio data and retrieve results
*/
private static final
String GOOGLE_RECOGNIZER_URL_NO_LANG
= "http://www.google.com/speech-api/v2/recognize?lang=en-
us&key=InsertMyKey&output=json";
. . .
. . .
. . .
private String rawRequest(byte[] bytes, String language) throws Exception {
System.out.println("in this second construct" );
URL url;
URLConnection urlConn;
OutputStream outputStream;
BufferedReader br;
// URL of Remote Script.
url = new URL(GOOGLE_RECOGNIZER_URL_NO_LANG);
// Open New URL connection channel.
urlConn = url.openConnection();
// we want to do output.
urlConn.setDoOutput(true);
// No caching
urlConn.setUseCaches(false);
// Specify the header content type.
urlConn.setRequestProperty("Content-Type", "audio/x-flac; rate=8000");
// Send POST output.
outputStream = urlConn.getOutputStream();
outputStream.write(bytes);
outputStream.close();
// Get response data.
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String response = br.readLine();
br.close();
return response;
}
picture of my key settings
This API endpoint release seems to be offered only for the community developers of the Chromium project; however, it is NOT possible to get additional quota, as mentioned in this documentation.
Instead, it is required to use the official v1 or v1p1beta1 endpoints to perform you speech recognition tasks. Additionally, I recommend you to take a look on the Client Libraries guides in order to get detailed information about the process to use Speech-to-Text API service by using programming languages, including Java.

How to HTTP POST parameters with Android/Java?

I'm struggling to find good examples on how to POST key value pairs to a URL with Android in Java.
Here is what the Android documentation says (and pretty much every other example):
URL url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
writeStream(out);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
} finally {
urlConnection.disconnect();
}
How do I implement writeStream?
Many other examples with POST put the parameters in the URL (a=1&b=2&c=3...), but then I could just use GET (?). And I don't want to place the parameters in the URL because that increases the chance of sensitive information to be logged on the server side.
Chrome POSTs data as such (body):
------WebKitFormBoundaryyr0AtYZxcOCCp7hA
Content-Disposition: form-data; name="parameterNameHere"
valueHere
------WebKitFormBoundaryyr0AtYZxcOCCp7hA--
Does the Android framework support this?
If not, are there any good libraries?
EDIT:
This is not a duplication of what was suggested. What was suggested does in no way answer the question, in that it does not show how to post with parameters, which is what this question is about.
There are many libraries out there that would help you achieve this. One of the libraries I use the most is OkHTTP. Include this library in your gradle and check the post from 'mauker' for an example on how to post
How to use OKHTTP to make a post request?

Unable to connect to omniture rest API 1.4

We are trying to connect to omniture rest API 1.4 using Java for report.Get. We are unable to create connection. The user id and password are working fine on UI but while making HTTP connection we are getting 400 bad request. Same code works fine with rest API 1.3 for company.reportSuites method. Code if failing while creating input stream. We did checked HTTP response code for connection at it is also coming 400.
public class OMTR_REST {
private static String USERNAME = "XXXXXXX";
private static String PASSWORD = "xXXXXXXXX";
private static String ENDPOINT = "https://api.omniture.com/admin/1.4/rest/"; //san jose endpoint, change for your company's datacenter
private OMTR_REST() {}
public static String callMethod(String method, String data) throws IOException {
URL url = new URL(ENDPOINT + "?method=" + method);
URLConnection connection = url.openConnection();
connection.addRequestProperty("X-WSSE", getHeader());
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
InputStream in = connection.getInputStream();
BufferedReader res = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer sBuffer = new StringBuffer();
String inputLine;
while ((inputLine = res.readLine()) != null)
sBuffer.append(inputLine);
res.close();
return sBuffer.toString();
There was a change in the API from version 1.3 to 1.4. The Get method now returns a status of 400 if the report in not ready. To me, it was a bad choice to return a HTTP 400 error (Bad request) when the report in not ready but that is what they are doing. See page 13 in the document below.
https://github.com/AdobeDocs/analytics-1.4-apis
I see few mistakes in your sample:
you should not use api.omniture.com for every request. First request should call api.omniture.com using Company.GetEndpoint method in order to get the correct endpoint, then use it for next requests.
when a wrong endpoint is used you could receive an HTTP 301 response. I'm not sure your implementation handle this case.
when you receive a HTTP 400 error (bad request). Well, that's exactly what has happened, in your example you're JSON writing directly into the body and many things could go wrong. Wrong type for a value, wrong upper/lower case for a key. Using a JAX-RS or another REST client should make your life simpler.
I have built a working Omniture REST API sample with JAX-RS where the model is clear easy to debug/modify.
Update
Recently I have found this:
https://github.com/Adobe-Marketing-Cloud/analytics-java-library

Reading from a URLConnection

I have a php page in my server that accepts a couple of POST requests and process them. Lets say it's a simple page and the output is simply an echoed statement. With the URLConnection I established from a Java program to send the POST request, I tried to get the input using the input stream got through connection.getInputStream(). But All I get is the source of the page(the whole php script) and not the output it produces. We shall avoid socket connections here. Can this be done with Url connection or HttpRequest? How?
class htttp{
public static void main(String a[]) throws IOException{
URL url=new URL("http://localhost/test.php");
URLConnection conn = url.openConnection();
//((HttpURLConnection) conn).setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write("Hello");
wr.flush();
wr.close();
InputStream ins = conn.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
String result = "";
while( (inputLine = in.readLine()) != null )
result += inputLine;
System.out.print(result);
}
}
I get the whole source of the webpage test.php in result. But I want only the output of the php script.
The reason you get the PHP source itself, rather than the output it should be rendering, is that your local HTTP server - receiving your request targeted at http://localhost/test.php - decided to serve back the PHP source, rather than forward the HTTP request to a PHP processor to render the output.
Why this happens? that has to do with your HTTP server's configuration; there might be a few reasons for that. For starters, you should validate your HTTP server's configuration.
Which HTTP server are you using on your machine?
What happens when you browse http://localhost/test.php through your browser?
The problem here is not the Java code - the problem lies with the web server. You need to investigate why your webserver is not executing your PHP script but sending it back raw. You can begin by testing using a simple PHP scipt which returns a fixed result and is accessed using a GET request (from a web browser). Once that is working you can test using the one that responds to POST requests.

Sending sms via java

I am going to send sms via java. The problem is the sms gateway ask me to send in this format
http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=
The problem how to call this from a java application is it possible or does it need special libraries? IS it using HttpURLConnection will do the job? Thank you.
A Sample code I have done below is this correct.
URL sendSms1 = new URL("http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert=");
URLConnection smsConn1 =
sendSms1.openConnection();
It's just an HTTP call, you don't need anything special in Java (or any modern language, I expect). Just build up the string as appropriate*, then make an HTTP request to that URL.
Take a peek at the Sun tutorial Reading from and Writing to a URLConnection if you need to pick up the basics of how to do the request part in Java. This uses the built-in classes, I'm sure there are dozens of libraries that handles connections in funky and/or convenient ways too, so by all means use one of those if you're familiar with it.
*One potential gotcha which might not have occurred to you - your query string arguments will have to be URL-encoded. So the + characters for example in the text parameter, are encoded spaces (which would have a different meaning in the URL). Likewise, if you wanted to send a ? character in one of your parameters, it would have to appear as %3F. Have a look at the accepted answer to HTTP URL Address Encoding in Java for an example of how you might build the URL string safely.
It looks like a simple GET request, you can use Apache HttpClient libarary for executing such a request. Have a look into a tutorial by Vogella here: http://www.vogella.de/articles/ApacheHttpClient/article.html for sample source code and explanations.
You can try to use java.net.URL library。
like this
// at this before you need to generate the urlString as "http://push1.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listen
ers.TextListener?userId=xxxxx&pass=xxxx&appid=xxxx&subappid=xxxx&msgtyp
e=1&contenttype=1&selfid=true&to=9810790590,9810549717&from=ACL&dlrre
q=true&text=This+is+a+test+msg+from+ACL&alert="
URL url = new URL(urlString);
// send sms
URLConnection urlConnection = url.openConnection();// open the url
// and you, also can get the feedback if you want
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
URL url = new URL("http://smscountry.com/SMSCwebservice.asp");
HttpURLConnection urlconnection = (HttpURLConnection) url.openConnection();
[Edit]
urlconnection.setRequestMethod("POST");
urlconnection.setRequestProperty("Content-Type","application/x-www-form-urlenc‌​oded");
urlconnection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(urlconnection.getOutputStream());
out.write(postData);
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlconnection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
retval += decodedString;
}

Categories

Resources