My java snippet looks like:
...
String type = "text/plain;charset=UTF-8";
URL url = new URL("http://xxx/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("OPTIONS");
conn.setRequestProperty("Content-Type", type);
...
When I sniff what this sends it sends a
OPTIONS / HTTP/1.1
which appears to be the default.
However, I actually want to send
OPTIONS * HTTP/1.0
How would I do this?
You can't do that with "plain" java.net.URLConnection. Consider replacing by Apache Commons HttpClient which is less bloated and more configureable. You can force HTTP 1.0 mode by setting http.protocol.version to HttpVersion.HTTP_1_0 in HttpClient#getParams(). You can find an example in this document.
I agree with the answer the following is the code using HTTPClient
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
Hope it helps some one..
Related
What I need to do is send POST request to specific URL with two parameters and when the request is sent, I need to redirect user to that link so that he would be able to access functionality.
So far, what I have managed to do from various examples is this:
private void postRemoteAdvisoryLink() throws IOException {
URL obj = new URL(KdrmApplicationContext.getRemoteAdvisoryUrlPath());
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setConnectTimeout(60000);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// For post only - start
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(("?auth=ssor&TransportKey=" + ssorTransportKey).getBytes());
os.flush();
os.close();
int responseCode = con.getResponseCode();
}
The problem is that now I get connection time out when trying to execute OutputStream os = con.getOutputStream(); line. Also, I still have no idea how to redirect user when request is completed.
Any ideas?
Using the basic Java URL classes would require you to manually handle the details of HTTP protocol - it's better to use libraries like Apache Http Components, as they deal with the underlying protocols for you. Some examples including POST requests can be found on their website.
Given the original question, the Timeout is likely related to host not responding or your Java application being unable to connect to given URL (due to no proxy configuration for example).
If you want to redirect a request based on the answer, you need to check the response headers and http status - if the status is 302, then there should be a header called Location, which will contain the URL you should make another request to.
Before getting an OutputStream, also make sure to set the Content-Length header (and ideally the Content-Type header as well).
I try to send a request from an Android device to a Nodejs server using
HttpURLConnection con = (HttpURLConnection) (new URL(IP + "/getrestaurant")).openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
con.getOutputStream().write("{'restaurant_id':'569a16e28dcdc5c8add2a8e0'}".getBytes("UTF-8"));
con.getOutputStream().flush();
con.getOutputStream().close();
When I print the received request from node js I get:
{
"{'restaurant_id':'569a16e28dcdc5c8add2a8e0'}": ""
}
instead of {'restaurant_id':'569a16e28dcdc5c8add2a8e0'}
How can I get it work? Thanks!
as the comment says(i have too low reputation to comment), {'restaurant_id':'569a16e28dcdc5c8add2a8e0'} is not valid context
also I advice you to use Koush Ion library for json requests . https://github.com/koush/ion
It is very convenient and easy to use for , give it a try . In one line all types of requests are done ,
The problem was that I needed con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
Can anybody tell me how to write a java client code to call restful web service with one parameter say email? I am trying the below code. But I am getting response as Success. Once this is success, I need the below XPHONE value. How to get this value?
XPHONE: 52-33-3669-7000
Here is the client code:
URL url = new URL("http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr=user.email");
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Accept",
"application/json");
conn.connect();
I think you just missing response body handling.
There is nice article about rest-client code: article.
You can try using the JavaLite Http client:
JavaLite Http
Depends on how API is implemented value can be in response body or even in header, so this info you should know from specification or ask in dev team.
First try to check if everything works fine using CURL or better "Advanced rest client" ( its extension in Chrome browser) if it works, than just transfer flow to your code. How to use advanced rest client look here
I used Jodd Http library to connect with the proxy:
ProxyInfo proxyInfoObj = new ProxyInfo(ProxyType.HTTP, "10.30.56.70", 8080, "", "");
SocketHttpConnectionProvider provider = new SocketHttpConnectionProvider();
provider.useProxy(proxyInfoObj);
HttpRequest request = HttpRequest.get(url);
request.method("GET");
request.charset("UTF-8");
HttpResponse response = request.open(provider).send();
result = response.bodyText();
But i got this error:
jodd.http.HttpException: HTTP: Invalid code
at jodd.http.net.HTTPProxySocketFactory.createHttpProxySocket(HTTPProxySocketFactory.java:113)
at jodd.http.net.HTTPProxySocketFactory.createSocket(HTTPProxySocketFactory.java:32)
If I use SOCKS4 type, the program hang and don't return anything. Can anyone help me?
But I can connect via proxy using following code:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.30.56.70", 8080));
HttpURLConnection connection =(HttpURLConnection)new URL("http://tvl.csmtalk.vn/api/sms/receive").openConnection(proxy);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "text/xml");
connection.setRequestProperty("Accept", "text/xml, application/xml");
connection.setRequestMethod("GET");
connection.connect();
For me both codes hangs. When I try Jodd, it hangs because it can not open proxy socket to 10.30.56.70:8080. When I try to
telnet 10.30.56.70 8080
from command line it hangs as well. It looks like proxy is not responding. (You can contact Jodd support if you need more details, or if you want to send some private data regarding the connectivity.)
btw, you don't need to:
request.method("GET");
request.charset("UTF-8");
as method is already set to GET by method get() and charset is not used for requests, but response (to set one if not set by server).
Can someone please explain how exactly the user credentials are passed to the server in the below code...
URL urlObj = new URL("https://javaguy.com");
HttpURLConnection conn = (HttpURLConnection) urlObj.openConnection(); conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "text/xml");
String userPassword = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(userPassword.getBytes());
String authStringEnc = new String(authEncBytes);
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
Is it part of the HTTP header? Just curious.
Thanks in advance.
You've answered your own question, but yes. The "Authorization" is part of the header.
You can read more about basic authentication on the wikipedia.
Then the javadoc isn't super clear, but the setRequestProperty should add the new property to the request header.
As a side note, I would urge you to consider using a library like HttpClient if you're planning on doing any http requests in a production system. Working directly with URL and URLConnection directly can be tricky. HttpClient isn't super easy to work with either, but it is easier then URL/URLConnection.
There are two HttpClient libraries, make sure you're working with version 4 (which is the latest version at the time of this post) and not version 3.